<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\BaseEnum;
use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationFormEnum;
use App\Enums\OpenShop\InvestmentPromotion\SpaceDesignErrorTrait;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Events\OpenShop\GenerateHeatMapImageEvent;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\AppletAuth;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Http\Resources\OpenShop\InvestmentPromotion\ProcessDetailResource;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Http\Resources\SiteLocation\AllClueSiteLocationDetailResource;
use App\Http\Resources\SiteLocation\ClueSiteLocationResource;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\ResourcesModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\MallSettleInShopInfoModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteLocationReplayModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationCustomerAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationHouseEvaluateModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationProductAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationWangguiRelationModel;
use App\Models\WaiMai\WaiMaiAnalysisModel;
use App\Models\Wanggui\CustomerDepartmentOperationLogModel;
use App\Models\Wanggui\CustomerDepartmentSiteLocationRelationModel;
use App\Models\Wanggui\WangguiDotWaimaiEstimateModel;
use App\Remote\Rms\RmsAreaRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Remote\Rms\RmsUserRoleRemote;
use App\Service\Common\AreaService;
use App\Service\Common\CommonService;
use App\Service\Common\HeatMapService;
use App\Service\Common\OssService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\NoticeService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Feishu\UploadFileResourceService;
use App\Service\OpenShop\FeishuMini\CustomerDepartmentService;
use App\Service\OpenShop\FeishuMini\ProgrammingService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Service\WaiMai\WaiMaiAnalysisService;
use App\Support\ChangeSupport;
use App\Support\FeishuMsgSupport;
use Carbon\Carbon;
use Exception;
use Guanguans\Notify\Factory;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Enumerable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use phpDocumentor\Reflection\Types\True_;

class SiteLocationService extends BaseService
{

    /**
     * 修改基本数据
     * @param $id
     * @param $params
     * @param $authUser
     * @throws Exception
     */
    public static function setSiteForm($id, $params, $authUser)
    {
        $info = OpenShopSiteLocationModel::query()
                                         ->where('id', $id)
                                         ->first();
        if (empty($info)) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NOT_EXIST);
        }

        if (in_array(
            $info->siteStatus,
            [OpenShopSiteLocationModel::SITE_STATUS_2, OpenShopSiteLocationModel::SITE_STATUS_4])
        ) {
            throw new ResponseHttpException(SpaceDesignErrorTrait::$ORDER_STATUS_NOT_SUPPORT_OPERATION);
        }

        $key  = key($params);
        $file = array_values($params);
        switch ($key) {
            case UploadFileResourceEnum::SHOP_ADDRESS_LEFT_PHOTO_DESC:
                //左视图
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_LEFT_PHOTO);
                break;
            case UploadFileResourceEnum::SHOP_ADDRESS_RIGHT_PHOTO_DESC:
                //右视图
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_RIGHT_PHOTO);
                break;
            case UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO_DESC:
                //正试图
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO);
                break;
            case UploadFileResourceEnum::SHOP_ADDRESS_SHOP_INNER_PHOTO_DESC:
                //店内图片
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_SHOP_INNER_PHOTO);
                break;
            case UploadFileResourceEnum::SHOP_ADDRESS_PANORAMA_PHOTO_DESC:
                //远景图
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_PANORAMA_PHOTO);
                break;
            case UploadFileResourceEnum::SHOP_ADDRESS_SHOP_VIDEO_DESC:
                //视频
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_VIDEO, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_ADDRESS_SHOP_VIDEO);
                break;
            case UploadFileResourceEnum::BUSINESS_INFO_PHOTO_DESC:
                //营业资料Photo
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::BUSINESS_INFO_PHOTO);
                break;
            case UploadFileResourceEnum::BUSINESS_INFO_PDF_DESC:
                //营业资料Pdf
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_PDF, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::BUSINESS_INFO_PDF);
                break;
            case UploadFileResourceEnum::PROJECT_MESSAGE_BAIDU_HEAT_MAP_DESC:
                //百度地图热力图
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::PROJECT_MESSAGE_BAIDU_HEAT_MAP);
                break;
            case UploadFileResourceEnum::MOVING_LING_MARKING_DESC:
                //先删除
                ResourcesModel::query()
                    ->where('businessId', $info->id)
                    ->where('business', ResourcesModel::BUSINESS_MOVING_LING_MARKING_DESC)
                    ->where('module', ResourcesModel::MODULE_TYPE_MOVING_LING_MARKING_DESC)
                    ->where('name', $key)
                    ->update([
                        'isDeleted' => 1
                    ]);
                $data = [];
                foreach($file[0] as $value) {
                    $data[] = [
                        'businessId'   => $info->id,
                        'module'       => ResourcesModel::MODULE_TYPE_MOVING_LING_MARKING_DESC,
                        'business'     => ResourcesModel::BUSINESS_MOVING_LING_MARKING_DESC,
                        'name'         => $key,
                        'url'          => $value['path'],
                        'isPublic'     => 1,
                        'extra'        => json_encode($value, true),
                        'createdAt'    => time(),
                        'updatedAt'    => time(),
                        'createdByUid' => $authUser['userId'] ?? 0,
                        'updatedByUid' => $authUser['userId'] ?? 0,
                    ];
                }
                //动线标注 支持附件采用新逻辑
                ResourcesModel::query()->insert($data);

                //self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser, $info['orderNo'], UploadFileResourceEnum::MOVING_LING_MARKING);

                break;
            case UploadFileResourceEnum::THE_CASH_REGISTER_PHOTO_DESC:
                // 收银机 说明文档
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::THE_CASH_REGISTER_PHOTO);
                break;
            case UploadFileResourceEnum::DOOR_DEPTH_WIDTH_PHOTO_DESC:
                // 门店进深图片
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::DOOR_DEPTH_WIDTH_PHOTO);
                break;
            case UploadFileResourceEnum::WALL_TAIL_USED_OLD_PHOTO_DESC:
                // 门店装修利旧
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::WALL_TAIL_USED_OLD_PHOTO);
                break;


            /************    证书资源提交   ************/
            case UploadFileResourceEnum::LICENSE_MAP[UploadFileResourceEnum::LICENSE_BUSINESS_PHOTO]:
                // 营业执照
                self::updateFileWithPosition(
                    $file[0],
                    OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::LICENSE_BUSINESS_PHOTO
                );
                break;

            case UploadFileResourceEnum::LICENSE_MAP[UploadFileResourceEnum::LICENSE_FOOD_PHOTO]:
                // 食品安全许可证
                self::updateFileWithPosition(
                    $file[0],
                    OpenShopUploadFileResourceModel::FILE_TYPE_IMG, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::LICENSE_FOOD_PHOTO
                );
                break;
            /************    证书资源提交   ************/

            case UploadFileResourceEnum::SITE_LOCATION_DATABASE_LIST[UploadFileResourceEnum::FLOOR_EXPLANATION_VIDEO]:
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_VIDEO, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::FLOOR_EXPLANATION_VIDEO);
                break;
            case UploadFileResourceEnum::SITE_LOCATION_DATABASE_LIST[UploadFileResourceEnum::PERIPHERAL_VIDEO]:
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_VIDEO, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::PERIPHERAL_VIDEO);
                break;
            case UploadFileResourceEnum::SITE_LOCATION_DATABASE_LIST[UploadFileResourceEnum::SHOP_IN_VIDEO]:
                self::updateFileWithPosition($file[0], OpenShopUploadFileResourceModel::FILE_TYPE_VIDEO, $authUser,
                    $info['orderNo'],
                    UploadFileResourceEnum::SHOP_IN_VIDEO);
                break;


            default :
                self::setSiteLocationById($id, $params, $authUser);
                break;

        }
    }

    /**
     * 选址上传文件
     *
     * @param $file
     * @param $type
     * @param $authUser
     * @param $orderNo
     * @param $position
     */
    public static function updateFileWithPosition($file, $type, $authUser, $orderNo, $position)
    {
        $mappingData = self::handleImg($file, $type, $position);
        $mappingData = self::arrayWalk($authUser, $orderNo, $mappingData);
        UploadFileResourceService::setFileListByPositionNoLog($orderNo, $position, $mappingData);
    }

    public static function setCustomerAnalysis($data, $authUser, $siteId)
    {
        $info = OpenShopSiteLocationModel::query()
                                         ->where('id', $siteId)
                                         ->first();

        if (empty($info)) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NOT_EXIST);
        }
        try {
            $orderNo = $info['orderNo'];
            DB::beginTransaction();
            foreach ($data as $value) {
                $week          = date("w", strtotime($value['time']));
                $value['week'] = ($week == 0 ? 7 : $week);

                if (
                    isset($value['id'])
                    &&
                    $info->customerAnalysisRel->where("id", $value["id"])->first()
                ) {
                    self::updateCustomerMapping($value, $orderNo, $authUser);
                } else {
                    if (!isset($value['id']) && !$info->customerAnalysisRel->where("time", strtotime($value['time']))
                                                                           ->first()) {
                        //新增
                        self::insertCustomerMapping($value, $orderNo, $authUser, $siteId);
                    }
                }
            }
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }
    }

    public static function updateCustomerMapping($value, $orderNo, $authUser)
    {
        $customerData = [
            'time'                        => strtotime($value['time']),
            'week'                        => $value['week'],
            'dateType'                    => $value['dateType'],
            'weather'                     => $value['weather'] ?? "",
            'temperature'                 => $value['temperature'],
            'afternoonNumber'             => $value['afternoonNumber'],
            'afternoonYoungProportion'    => $value['afternoonYoungProportion'],
            'afternoonTeaNumber'          => $value['afternoonTeaNumber'],
            'afternoonTeaYoungProportion' => $value['afternoonTeaYoungProportion'],
            'nightNumber'                 => $value['nightNumber'],
            'nightYoungProportion'        => $value['nightYoungProportion'],
            'nightSnackNumber'            => $value['nightSnackNumber'],
            'nightSnackYoungProportion'   => $value['nightSnackYoungProportion'],
            'createdAt'                   => time(),
            'createdByUid'                => $authUser['userId'] ?? 0,
            'updatedAt'                   => time(),
            'updatedByUid'                => $authUser['userId'] ?? 0,
        ];
        OpenShopSiteLocationCustomerAnalysisModel::query()
                                                 ->where('id', $value['id'])
                                                 ->update($customerData);
        $mappingData  = self::getCustomerAnalysisMapping($value['afternoonPhoto'], $value['afternoonTeaPhoto'],
            $value['nightPhoto'], $value['nightSnackPhoto']);
        $mappingData  = self::arrayWalk($authUser, $orderNo, $mappingData, $value['id']);
        $positionList = UploadFileResourceEnum::CUSTOMER_ANALYSIS_LIST;
        UploadFileResourceService::setFileListByPositionList($orderNo, $positionList, $mappingData, $value['id']);
    }

    public static function insertCustomerMapping($value, $orderNo, $authUser, $siteId)
    {
        $customerInsertData = [
            'siteId'                      => $siteId,
            "orderNo"                     => $orderNo,
            'time'                        => strtotime($value['time']),
            'week'                        => $value['week'],
            'dateType'                    => $value['dateType'],
            'weather'                     => $value['weather'] ?? "",
            'temperature'                 => $value['temperature'],
            'afternoonNumber'             => $value['afternoonNumber'],
            'afternoonYoungProportion'    => $value['afternoonYoungProportion'],
            'afternoonTeaNumber'          => $value['afternoonTeaNumber'],
            'afternoonTeaYoungProportion' => $value['afternoonTeaYoungProportion'],
            'nightNumber'                 => $value['nightNumber'],
            'nightYoungProportion'        => $value['nightYoungProportion'],
            'nightSnackNumber'            => $value['nightSnackNumber'],
            'nightSnackYoungProportion'   => $value['nightSnackYoungProportion'],
            'createdAt'                   => time(),
            'createdByUid'                => $authUser['userId'] ?? 0,
            'updatedAt'                   => time(),
            'updatedByUid'                => $authUser['userId'] ?? 0,
        ];
        $id                 = OpenShopSiteLocationCustomerAnalysisModel::query()
                                                                       ->insertGetId($customerInsertData);
        $mappingData        = self::getCustomerAnalysisMapping($value['afternoonPhoto'], $value['afternoonTeaPhoto'],
            $value['nightPhoto'], $value['nightSnackPhoto']);
        $mappingData        = self::arrayWalk($authUser, $orderNo, $mappingData, $id);
        $positionList       = UploadFileResourceEnum::CUSTOMER_ANALYSIS_LIST;
        UploadFileResourceService::setFileListByPositionList($orderNo, $positionList, $mappingData, $id);
    }

    public static function getCustomerAnalysisMapping(
        $afternoonPhoto,
        $afternoonTeaPhoto,
        $nightPhoto,
        $nightSnackPhoto
    ) {
        $afternoonPhoto    = self::handleImg($afternoonPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::AFTERNOON_MARKET_PHOTO);
        $afternoonTeaPhoto = self::handleImg($afternoonTeaPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::AFTERNOON_TEA_MARKET_PHOTO);
        $nightPhoto        = self::handleImg($nightPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::NIGHT_MARKET_PHOTO);
        $nightSnackPhoto   = self::handleImg($nightSnackPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::NIGHT_SNACK_MARKET_PHOTO);
        $mappingData       = [];
        $mappingData       = array_merge($mappingData, $afternoonPhoto, $afternoonTeaPhoto, $nightPhoto,
            $nightSnackPhoto);
        return $mappingData;
    }


    public static function setProductAnalysis($data, $authUser, $siteId)
    {
        $info = OpenShopSiteLocationModel::query()
                                         ->where('id', $siteId)
                                         ->first();
        if (empty($info)) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NOT_EXIST);
        }
        try {
            $orderNo = $info['orderNo'];
            DB::beginTransaction();
            foreach ($data as $value) {
                if (isset($value['id'])) {
                    self::updateProductMapping($value, $orderNo, $authUser);
                } else {
                    self::insertProductMapping($value, $siteId, $orderNo, $authUser);
                }

            }
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }

    }

    public static function updateProductMapping($value, $orderNo, $authUser)
    {
        //修改关联表
        $customerData = [
            'type'               => $value['type'],
            'productName'        => $value['productName'],
            'elemNumber'         => $value['elemNumber'],
            'elemUnitPrice'      => $value['elemUnitPrice'],
            'meituanNumber'      => $value['meituanNumber'],
            'meituanUnitPrice'   => $value['meituanUnitPrice'],
            'specialExplanation' => $value["specialExplanation"] ?? "",
            'createdAt'          => time(),
            'createdByUid'       => $authUser['userId'] ?? 0,
            'updatedAt'          => time(),
            'updatedByUid'       => $authUser['userId'] ?? 0,
        ];
        OpenShopSiteLocationProductAnalysisModel::query()
                                                ->where('id', $value['id'])
                                                ->update($customerData);
        $mappingData  = self::getProductAnalysisMapping(
            $value['shopInnerPhoto'],
            $value['dazhongPhoto'],
            $value['elemPhoto'],
            $value['meituanPhoto'],
            $value["eatInGraduationReceiptPhoto"]
        );
        $mappingData  = self::arrayWalk($authUser, $orderNo, $mappingData, $value['id']);
        $positionList = UploadFileResourceEnum::PRODUCT_ANALYSIS_LIST;
        UploadFileResourceService::setFileListByPositionList($orderNo, $positionList, $mappingData, $value['id']);
    }

    public static function insertProductMapping($value, $siteId, $orderNo, $authUser)
    {
        //修改关联表
        $customerData = [
            "orderNo"            => $orderNo,
            "siteId"             => $siteId,
            'type'               => $value['type'],
            'productName'        => $value['productName'],
            'elemNumber'         => $value['elemNumber'],
            'elemUnitPrice'      => $value['elemUnitPrice'],
            'meituanNumber'      => $value['meituanNumber'],
            'meituanUnitPrice'   => $value['meituanUnitPrice'],
            'specialExplanation' => $value["specialExplanation"] ?? "",
            'createdAt'          => time(),
            'createdByUid'       => $authUser['userId'] ?? 0,
            'updatedAt'          => time(),
            'updatedByUid'       => $authUser['userId'] ?? 0,
        ];
        $id           = OpenShopSiteLocationProductAnalysisModel::query()
                                                                ->insertGetId($customerData);
        $mappingData  = self::getProductAnalysisMapping(
            $value['shopInnerPhoto'],
            $value['dazhongPhoto'],
            $value['elemPhoto'],
            $value['meituanPhoto'],
            $value["eatInGraduationReceiptPhoto"]
        );
        $mappingData  = self::arrayWalk($authUser, $orderNo, $mappingData, $id);
        $positionList = UploadFileResourceEnum::PRODUCT_ANALYSIS_LIST;
        UploadFileResourceService::setFileListByPositionList($orderNo, $positionList, $mappingData, $id);
    }

    public static function getProductAnalysisMapping(
        $shopInnerPhoto,
        $dazhongPhoto,
        $elemPhoto,
        $meituanPhoto,
        $eatInGraduationReceiptPhoto
    ): array {
        $shopInnerPhoto              = self::handleImg($shopInnerPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::PRODUCT_SHOP_INNER_PHOTO);
        $dazhongPhoto                = self::handleImg($dazhongPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::PRODUCT_SHOP_DAZHONG_PHOTO);
        $elemPhoto                   = self::handleImg($elemPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::PRODUCT_SHOP_ELEM_PHOTO);
        $meituanPhoto                = self::handleImg($meituanPhoto, OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::PRODUCT_SHOP_MEITUAN_PHOTO);
        $eatInGraduationReceiptPhoto = self::handleImg($eatInGraduationReceiptPhoto,
            OpenShopUploadFileResourceModel::FILE_TYPE_IMG,
            UploadFileResourceEnum::PRODUCT_EAT_IN_GRADUATION_RECEIPT_PHOTO);
        return array_merge($shopInnerPhoto, $dazhongPhoto, $elemPhoto, $meituanPhoto, $eatInGraduationReceiptPhoto);
    }


    public static function setSiteLocationById($id, $data, $authUser)
    {
        try {
            $key = key($data);
//
//            switch ($key) {
//                case 'selectTime':
//                case 'openTime':
//                    $data[$key] = strtotime($data[$key]);
//                    break;
//                case 'week':
//                    $data[$key] = BaseEnum::WEEK_MAPPING_REVERSE[$data[$key]] ?? 0;
//                    break;
//            }

            $order = OpenShopSiteLocationModel::query()
                                              ->where('id', $id)
                                              ->first();

            if (is_array($data[$key])) {
                if ($key === "leaseFiles") {
                    $data[$key] = str_replace(str_replace('/', '\/', FileUtil::domain()) . '\/', '%s', json_encode($data[$key]));
                } else {
                    $data[$key] = implode(',', $data[$key]);
                }
            } elseif (in_array($key, OpenShopSiteLocationModel::JSON_FIELD)) {
                $jsonField = $order->jsonField;
                if (mb_strlen($jsonField)) {
                    $arrField = json_decode($jsonField, true);
                }
                $arrField[$key] = $data[$key];
                $data           = [
                  'jsonField' => json_encode($arrField, JSON_UNESCAPED_UNICODE),
                ];
            } else {
                switch ($key) {
                    case "selectTime":
                    case "openTime":
                    case "signatureTime":
                        $data[$key] = strtotime($data[$key]);
                        break;
                    case "address":
                        $data[$key] = str_replace("\n", '', $data[$key]);
                        break;
                    case "messageFrom":
                        if ($order->messageFrom == SiteLocationEnum::MESSAGE_FROM_TYPE_3 && $data[$key] != SiteLocationEnum::MESSAGE_FROM_TYPE_3) {
                            //远程切换  删除客群分析数据
                            OpenShopSiteLocationCustomerAnalysisModel::query()->where("siteId", $order->id)->delete();
                            OpenShopUploadFileResourceModel::query()
                                                           ->where("orderNo", $order->orderNo)
                                                           ->whereIn("position",
                                                               array_keys(UploadFileResourceEnum::CUSTOMER_ANALYSIS_DATABASE_LIST))
                                                           ->delete();
                        }
                        break;
                }
            }
//            $data['createdAt']    = time();
//            $data['createdByUid'] = $authUser['userId'] ?? 0;
            $data['updatedAt']    = time();
            $data['updatedByUid'] = $authUser['userId'] ?? 0;


            // 28-自选  29-嘴点
            if ($order->posLine == 29) {
                $data['customerUnitPriceEstimation'] = 25;
            } elseif ($order->posLine == 28) {
                $data['customerUnitPriceEstimation'] = 30;
            }

            if (!empty($data['shopName'])) {
                switch ($order->source) {
                    case OpenShopSiteLocationModel::SOURCE_OPEN_SHOP:
                        app()->get('request')->userInfo = (object)['id' => $authUser['userId']];
//                        ShopService::updateShopName($order->orderNo, $data['shopName'] ?? '');
                        //unset($data['shopName']);  入库保存
                        break;
                    case OpenShopSiteLocationModel::SOURCE_HOUSING:
                        if ($order->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6) {
                            app()->get('request')->userInfo = (object)['id' => $authUser['userId']];
//                            ShopService::updateShopName($order->orderNo, $data['shopName'] ?? '');
                        }
                        break;
                }
            }
            unset($data["s"]);
            unset($data["nearbyShopName"]);  //附近门店
            OpenShopSiteLocationModel::query()
                                     ->where('id', $id)
                                     ->update($data);

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 处理图片
     * @param $image
     * @param $type
     * @param $position
     * @return array
     */
    public static function handleImg($image, $type, $position)
    {
        $data = [];
        foreach ((array)$image as $key => $value) {
            $data[$key]['type']     = $type;
            $data[$key]['url']      = getPrivateFileKey($value);
            $data[$key]['position'] = $position;
        }
        return $data;
    }

    /**
     * 组装数据
     * @param $authUser
     * @param $orderNo
     * @param $mappingData
     * @param int $id
     * @return mixed
     */
    public static function arrayWalk($authUser, $orderNo, $mappingData, $id = 0)
    {
        array_walk($mappingData, function (&$value, $key) use ($authUser, $orderNo, $id) {
            $value['createdAt']    = time();
            $value['createdByUid'] = $authUser['userId'] ?? 0;
            $value['updatedAt']    = time();
            $value['updatedByUid'] = $authUser['userId'] ?? 0;
            $value['businessId']   = $id;
            $value['orderNo']      = $orderNo;
            $value['isPublic']     = 1;
        });
        return $mappingData;
    }

    /**
     * @var OpenShopSiteLocationModel|null
     */
    public static ?OpenShopSiteLocationModel $siteLocationModel = null;

    /**
     * @var SiteLocationFormEnum|null
     */
    public static ?SiteLocationFormEnum $siteLocationFormEnum = null;


    public static function isSolicitBusinessManager(int $uid)
    {
        //判断是否有招商经理职位
        $isSolicitBusinessManager = (function () use ($uid) {
            [$userRole, $platformRole] = array_values(RmsUserRoleRemote::getUserRoleByUserId([$uid]));
            if (empty($userRole)) {
                return false;
            } else {
                return in_array($platformRole["openShop"]["solicitBusinessManagerRoleId"],
                    current($userRole)["userRole"]);
            }
        });

        return $isSolicitBusinessManager();
    }

    /**
     * @param int $siteId
     * @return array[]
     * @throws GuzzleException
     */
    public static function getSiteFormContent(int $siteId): array
    {
        self::$siteLocationModel = OpenShopSiteLocationModel::getSiteForm($siteId);

        $nearbyShopName = ShopService::getShopNameByCode(self::$siteLocationModel->nearbyShopCode);
        // try {
        //     $shopInfo = self::$siteLocationModel->nearbyShopCode ? (GuanyuanDataService::newShopList(self::$siteLocationModel->nearbyShopCode)[0] ?? []) : [];
        // } catch (\Exception $exception) {
        //     $shopInfo = [];
        // }
        // if (!empty($shopInfo)) $nearbyShopName = '【' . ($shopInfo['状态'] ?? '-') . '】'. ($shopInfo['门店名称'] ?? '-');

        self::$siteLocationModel->setAttribute(
            "isSolicitBusinessManager",
            self::isSolicitBusinessManager(request()->user()->id)
        );
        self::$siteLocationModel->setAttribute("nearbyShopName", $nearbyShopName);

        self::$siteLocationFormEnum = new SiteLocationFormEnum(collect(self::$siteLocationModel->getAttributes()));

        return self::getFormContent();
    }

    /**
     * 获取详情
     * @param $siteId
     * @param $authUser
     * @param string|null $field
     * @return array
     * @throws GuzzleException
     */
    public static function getSiteForm($siteId, $authUser, ?string $field = '', $from = 0): array
    {
        self::$siteLocationModel = OpenShopSiteLocationModel::getSiteForm($siteId);
        switch ($from) {
            case 1:
                $isSolicitBusinessManager = false;
                break;
            default:
                if (
                    request()->user()->id == self::$siteLocationModel->createdByUid
                    ||
                    self::$siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11
                ) {
                    $isSolicitBusinessManager = self::isSolicitBusinessManager(self::$siteLocationModel->createdByUid);
                } else {
                    $isSolicitBusinessManager = false;
                }
                break;
        }

        self::$siteLocationModel = OpenShopSiteLocationModel::getSiteForm($siteId);
        self::$siteLocationModel->setAttribute("isSolicitBusinessManager", $isSolicitBusinessManager);

        $templateData = self::templateElement($field);

        /**
         * 判断是否能再次编辑-如果状态是已提交和已完成 禁止修改
         */
        if (in_array(self::$siteLocationModel->siteStatus, [
                OpenShopSiteLocationModel::SITE_STATUS_2,
                OpenShopSiteLocationModel::SITE_STATUS_10,
                OpenShopSiteLocationModel::SITE_STATUS_4,
                OpenShopSiteLocationModel::SITE_STATUS_11
            ]) || in_array(self::$siteLocationModel->clueStatus, [
                OpenShopSiteLocationModel::CLUE_STATUS_5,
                OpenShopSiteLocationModel::CLUE_STATUS_6,
                //OpenShopSiteLocationModel::CLUE_STATUS_11,
                //OpenShopSiteLocationModel::CLUE_STATUS_3,
            ]) || self::$siteLocationModel->developConsultantId != $authUser['userId']) {
            if (!empty($field)) {
                $templateData = [$templateData];
            }

            $imgFields = collect(array_merge(
                array_values(UploadFileResourceEnum::SITE_LOCATION_DATABASE_LIST),
                array_values(UploadFileResourceEnum::CUSTOMER_ANALYSIS_DATABASE_LIST),
                array_values(UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST),
                array_values(UploadFileResourceEnum::CLUE_SITE_LOCATION_MAP)
            ))->unique()->diff(["clueVideos", "shopVideo"])->toArray();

            // 新增 disable 状态
            foreach ($templateData as &$sonData) {
                if ($sonData['key'] == 'estimationCustomer') {
                    continue;
                }
                foreach ($sonData['value'] as &$data) {
                    if (!empty($data['value'])) {
                        foreach ($data['value'] as &$value) {
                            $value['disabled'] = true;
                            $value['icon']     = '';
                            if (empty($value["value"]) && in_array($value["field"], $imgFields)) {
                                $value["value"] = ["https://file.51kuafu.com/33/98/9f0b22ff2b07cd956e4eb2cdaa92fb7336f877168949151bf2d69a16a7d3.png"];
                            }
                            if (in_array($value['field'], ['shopType', 'siteSelection', 'sellingCategory', 'menuLevel', 'posLine'])) {
                                if (strlen($value['value']) == 1 && $value['value'] == 0) {
                                    $value['value'] = '';
                                }
                            }
                        }
                    }
                    if (!empty($data['tab1'])) {
                        $sonData['disable'] = true;
                        foreach ($data['tab1'] as &$tabValue) {
                            $tabValue['disabled'] = true;
                            $tabValue['icon']     = '';
                            if (empty($tabValue["value"]) && in_array($tabValue["field"], $imgFields)) {
                                $tabValue["value"] = ["https://file.51kuafu.com/33/98/9f0b22ff2b07cd956e4eb2cdaa92fb7336f877168949151bf2d69a16a7d3.png"];
                            }
                        }
                    }
                }
            }


            unset($sonData);
            // 删除客群分析-新的空白数据
            foreach ($templateData as &$sonData) {
                switch ($sonData['key']) {
                    case 'customers':
                        foreach ($sonData['value'] as $key => &$datum) {
                            if (!$datum['isTemplate'] && empty($datum['id'])) {
                                unset($sonData['value'][$key]);
                            }
                        }
                        $sonData['value'] = array_values($sonData['value']);
                        break;
                }
            }

            if (!empty($field)) {
                $templateData = $templateData[0];
            }
        }

        $isShowButton   = false;  // 房源相关
        $isReplayButton = false;  // 展示立即复盘

        /***结束***/
        if (self::$siteLocationModel->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP) {
            $status = self::$siteLocationModel->siteStatus;
        }

        // 状态输出
        if (self::$siteLocationModel->source == OpenShopSiteLocationModel::SOURCE_HOUSING) {
            if (in_array(self::$siteLocationModel->clueStatus, [
                OpenShopSiteLocationModel::CLUE_STATUS_0,
                OpenShopSiteLocationModel::CLUE_STATUS_5,
                OpenShopSiteLocationModel::CLUE_STATUS_6,
                OpenShopSiteLocationModel::CLUE_STATUS_10
            ])) {
                $status = OpenShopSiteLocationModel::CLUE_STATUS_4;
            }
            if (self::$siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_3) {
                $status = OpenShopSiteLocationModel::CLUE_STATUS_2;
            }
            if (self::$siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11) {
                $status = OpenShopSiteLocationModel::CLUE_STATUS_11;
            }
        }

        //要判断是历史数据或者是否为房源  已当前新加的必填字段『shopModelType』作为依据
        if (self::$siteLocationModel->shopModelType) {
            $isShowButton = true;
        }

        // 表单审批按钮
        if (in_array($authUser['userId'], explode(',', self::$siteLocationModel->handler))
            && (
                in_array(self::$siteLocationModel->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_13,
                    OpenShopSiteLocationModel::CLUE_STATUS_11,
                    OpenShopSiteLocationModel::CLUE_STATUS_3
                ])
                ||
                in_array(self::$siteLocationModel->siteStatus, [
                    OpenShopSiteLocationModel::SITE_STATUS_2,
                    OpenShopSiteLocationModel::SITE_STATUS_10,
                    OpenShopSiteLocationModel::SITE_STATUS_11,
                    OpenShopSiteLocationModel::SITE_STATUS_22
                ])
            )
        ) {
            $isShowApprovalButton = true;
        } else {
            $isShowApprovalButton = false;
        }

        //判断是否为复盘  展示立即复盘
        if (self::$siteLocationModel->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && self::$siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4) {
            //复盘人
            $replayUserIds = [];
            OpenShopSiteLocationReplayModel::query()
                ->where('orderNo', self::$siteLocationModel->orderNo)
                ->get()
                ->each(function ($item) use (&$replayUserIds) {
                    if (!mb_strlen($item->content)) {
                        $replayUserIds[] = $item->createdByUid;
                    }
                });
            if (in_array($authUser['userId'], $replayUserIds)) {
                $isReplayButton = true;
            }
        }

        //判断是否为开发经理
        if ($authUser['userId'] != self::$siteLocationModel->developConsultantId) {
            //新增状态为-1 为了控制待修改时按钮隐藏
            $status = -1;
        }
        switch (self::$siteLocationModel->source) {
            case OpenShopSiteLocationModel::SOURCE_OPEN_SHOP:
                $title = '门店选址调查-' . (int)optional(self::$siteLocationModel->signOrderRel)->shopCode;
                break;
            case OpenShopSiteLocationModel::SOURCE_HOUSING:
                $title = '房源线索调查-' . self::$siteLocationModel->orderNo;
                break;
            default:
                $title = '';
        }

        return [
            'siteInfo'     => [
                'title'                => $title,
                'orderNo'              => self::$siteLocationModel->orderNo,
                'mallStatus'           => self::$siteLocationModel->mallStatus,
                'isWhiteList'          => self::$siteLocationModel->isWhiteList,
                'shopModelType'        => self::$siteLocationModel->shopModelType,
                'mallId'               => self::$siteLocationModel->mallId,
                'cityType'             => self::$siteLocationModel->cityType,
                'mallGrade'            => in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE]) ? (self::$siteLocationModel->mallGrade ?: 'C级') : '',
                'siteStatus'           => $status ?? 0,
                'status'               => self::$siteLocationModel->status,
                'replay'               => self::getReplayByOrderNo(
                    self::$siteLocationModel->orderNo,
                    $authUser['userId']
                ),
                'isShowButton'         => $isShowButton,
                'isReplayButton'       => $isReplayButton,
                'isShowApprovalButton' => $isShowApprovalButton,
                "approval"             => self::getApprovalRecord(self::$siteLocationModel->orderNo),
            ],
            'templateData' => $templateData
        ];
    }

    public static function getLeaseContractForm($siteId, $authUser)
    {
        self::$siteLocationModel = OpenShopSiteLocationModel::getSiteForm($siteId);
        if (mb_strlen(self::$siteLocationModel->leaseFiles)) {
            self::$siteLocationModel->leaseFiles = json_decode(str_replace('%s', str_replace('/', '\/', FileUtil::domain()) . '\/', self::$siteLocationModel->leaseFiles), true);
        } else {
            self::$siteLocationModel->leaseFiles = [];
        }
        self::$siteLocationModel->ctRentPaymentCycle = self::$siteLocationModel->ctRentPaymentCycle ?: '';
        self::$siteLocationModel->ctRentType         = self::$siteLocationModel->ctRentType ?: '';
        self::$siteLocationFormEnum = new SiteLocationFormEnum(
            collect(self::$siteLocationModel->toArray()),
            self::$siteLocationModel->source
        );

        //获得合同的开始时间及其结束时间
        $jsonField = mb_strlen(self::$siteLocationModel->jsonField) ? json_decode(self::$siteLocationModel->jsonField, true) : [];

        $templateData = [
            'sort'  => 100,
            'key'   => 'leaseInfo',
            'name'  => '租赁信息',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('leaseFiles', self::$siteLocationModel->leaseFiles), // 租赁合同
                        self::getSiteLocationField('signatureTime', self::$siteLocationModel->signatureTime ? formatDateYmd(self::$siteLocationModel->signatureTime) : ''), // 签署时间
                        self::getSiteLocationField('ctRentType', '', self::$siteLocationModel->rentType), // 计租方式
                        self::getSiteLocationField('ctFixedRent', '', self::$siteLocationModel->fixedRent / 100), // 固定租金
                        self::getSiteLocationField('ctRemind', '', self::$siteLocationModel->remind), // 提点百分比
                        self::getSiteLocationField('ctRentPaymentCycle', '', self::$siteLocationModel->rentPaymentCycle), // 租金支付周期
                        self::getSiteLocationField('ctDeposit', '', self::$siteLocationModel->deposit), // 押金
                        self::getSiteLocationField('ctLeaseTerm', '', self::$siteLocationModel->leaseTerm), // 租期
                        self::getSiteLocationField('ctStartTime', $jsonField['ctStartTime'] ?? ''), // 合同开始时间
                        self::getSiteLocationField('ctEndTime', $jsonField['ctEndTime'] ?? ''), // 合同结束时间
                        self::getSiteLocationField('ctRentFreePeriod', '', self::$siteLocationModel->rentFreePeriod), // 免租期
                        self::getSiteLocationField('ctPropertyFee', '', self::$siteLocationModel->propertyFee), // 物业费
                        self::getSiteLocationField('ctMobilizationFee', '', self::$siteLocationModel->mobilizationFee), // 进场费
                        self::getSiteLocationField('ctTransferFee', '', self::$siteLocationModel->transferFee), // 转让费
                        self::getSiteLocationField('ctBond', '', self::$siteLocationModel->bond), // 保证金
                        self::getSiteLocationField("ctManageFee", '', self::$siteLocationModel->manageFee), // 管理费
                        self::getSiteLocationField("ctSponsorshipFee", '', self::$siteLocationModel->sponsorshipFee), // 赞助费
                        self::getSiteLocationField("ctPromotionFee", '', self::$siteLocationModel->promotionFee), // 推广费
                        self::getSiteLocationField("ctOtherFee", '', self::$siteLocationModel->otherFee), // 其他费用
                        self::getSiteLocationField("expenseDifferDesc"), // 费用不一致说明
                    ]
                ]

            ]
        ];

        //表单控制
        if (self::$siteLocationModel->ctRentType == SiteLocationEnum::RENT_TYPE_1) {
            $templateData['value']['tab1']['value'][4]['display'] = 'none';
        }
        if (self::$siteLocationModel->ctRentType == SiteLocationEnum::RENT_TYPE_2) {
            $templateData['value']['tab1']['value'][3]['display'] = 'none';
        }

        if (self::$siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 || $authUser['userId'] != self::$siteLocationModel->developConsultantId) {
            foreach ($templateData['value']['tab1']['value'] as $k => $input) {
                $templateData['value']['tab1']['value'][$k]['disabled'] = true;
            }
        }

        $verifyPersonnel = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL);

        return [
            'isAudit'       => in_array($authUser['userId'], $verifyPersonnel) && self::$siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_22,  // 合同驳回
            'templatedData' => $templateData,
            'orderNo'       => self::$siteLocationModel->orderNo,
            'isSubmit'      => self::$siteLocationModel->developConsultantId == $authUser['userId'] && self::$siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_21,
        ];
    }


    /**
     * 校验当天数据是否存在
     */
    public static function checkCustomerData($customerAnalysisRel): bool
    {
        $result = false;
        $data   = date('Y-m-d');
        // 判断是否存在当天数据
        foreach ($customerAnalysisRel as $checkData) {
            if (empty($checkData['time'])) {
                continue;
            }

            if (date('Y-m-d', $checkData['time']) == $data) {
                $result = true;
                break;
            }

        }

        return $result;
    }


    public static function getWeek()
    {
        $data = date("w", time());
        if ($data == 0) {
            $data = 7;
        }
        return $data;
    }

    /**
     * 客群分析
     *
     * @param OpenShopSiteLocationModel $openShopSiteLocationModel
     * @return array
     */
    public static function getCustomerElement(OpenShopSiteLocationModel $openShopSiteLocationModel): array
    {
        $customerAnalysisRel = $openShopSiteLocationModel->customerAnalysisRel ?? new Collection();
        $messageFrom         = $openShopSiteLocationModel->messageFrom;
        // 判断是否存在当天数据
        if (!self::checkCustomerData($customerAnalysisRel)) {
            $customerAnalysisRel->push(collect(['time' => time(), 'week' => self::getWeek()]));
        }


        if (
            in_array($openShopSiteLocationModel->siteStatus, [2, 4])
            ||
            in_array($openShopSiteLocationModel->clueStatus, [
                OpenShopSiteLocationModel::CLUE_STATUS_5,
                OpenShopSiteLocationModel::CLUE_STATUS_6,
                OpenShopSiteLocationModel::CLUE_STATUS_3
            ])
        ) {

            $customerAnalysisRel = $customerAnalysisRel->filter(function ($v) {
                foreach (OpenShopSiteLocationCustomerAnalysisModel::$filterFields as $field) {
                    if (!empty($v->{$field})) {
                        return true;
                    }
                }
                return false;
            })->values();

        }

//        $customerAnalysisRel->push(collect(['time' => time(), 'week' => self::getWeek(), 'template' => true]));
        $result = [];
        foreach ($customerAnalysisRel as $customer) {
            $customerEnum = new SiteLocationFormEnum(collect($customer->toArray()));

            $time = isset($customer) ? date('Y-m-d', $customer['time']) : date('Y-m-d');

            if (!empty(BaseEnum::WEEK_MAPPING[$customer['week']])) {
                $week = BaseEnum::WEEK_MAPPING[$customer['week']];
            } else {
                $week = '';
            }

            $isTemplate = (bool)(isset($customer["template"]) ? $customer["template"] : false);
            $data       = [
                'name'       => $time . ' ' . $week,
                'id'         => $customer['id'] ?? 0,
                'isTemplate' => $isTemplate,
                'tab1'       => collect(array_merge(
                    [
                        $customerEnum->getSiteLocationField('time', $time),
                        $customerEnum->getSiteLocationField('week', $week),
                        $customerEnum->getSiteLocationField('dateType'),
                        $customerEnum->getSiteLocationField('weather'),
                        $customerEnum->getSiteLocationField('temperature'),
                        $customerEnum->getSiteLocationField('afternoonNumber'),
                        $customerEnum->getSiteLocationField('afternoonYoungProportion'),
                        $customerEnum->getSiteLocationField('afternoonPhoto', "", $customer['id'] ?? 0),
                        $customerEnum->getSiteLocationField('afternoonTeaNumber'),
                        $customerEnum->getSiteLocationField('afternoonTeaYoungProportion'),
                        $customerEnum->getSiteLocationField(
                            'afternoonTeaPhoto', "", $customer['id'] ?? 0
                        ),
                        $customerEnum->getSiteLocationField('nightNumber'),
                        $customerEnum->getSiteLocationField('nightYoungProportion'),
                        $customerEnum->getSiteLocationField(
                            'nightPhoto', "", $customer['id'] ?? 0
                        ),
                        $customerEnum->getSiteLocationField('nightSnackNumber'),
                        $customerEnum->getSiteLocationField('nightSnackYoungProportion'),
                        $customerEnum->getSiteLocationField(
                            'nightSnackPhoto', "", $customer['id'] ?? 0
                        ),
                    ]))->values()->toArray()
            ];

            if ($data['id'] === 0) {
                unset($data['id']);
            }

            $result[] = $data;
        }

        $customerEnum = new SiteLocationFormEnum(collect([]));
        array_push($result, [

            'name'       => "",
            'id'         => 0,
            'isTemplate' => true,
            'tab1'       => collect(
                [
                    $customerEnum::unit('time', '选择日期', true, 'datetime'),
                    $customerEnum->getSiteLocationField('week', self::getWeek()),
                    $customerEnum::unit('dateType', '日期类型', false, 'radio',
                        SiteLocationEnum::getOptionsByConst(SiteLocationEnum::DATE_TYPE_TEXT),
                        ['icon' => '', 'disabled' => false, 'value' => '']),
                    $customerEnum::unit('weather', '天气', false, 'text', [], ['disabled' => false]),
                    $customerEnum->getSiteLocationField('temperature'),
                    $customerEnum->getSiteLocationField('afternoonNumber'),
                    $customerEnum->getSiteLocationField('afternoonYoungProportion'),
                    $customerEnum->getSiteLocationField('afternoonPhoto'),
                    $customerEnum->getSiteLocationField('afternoonTeaNumber'),
                    $customerEnum->getSiteLocationField('afternoonTeaYoungProportion'),
                    $customerEnum->getSiteLocationField('afternoonTeaPhoto'),
                    $customerEnum->getSiteLocationField('nightNumber'),
                    $customerEnum->getSiteLocationField('nightYoungProportion'),
                    $customerEnum->getSiteLocationField('nightPhoto'),
                    $customerEnum->getSiteLocationField('nightSnackNumber'),
                    $customerEnum->getSiteLocationField('nightSnackYoungProportion'),
                    $customerEnum->getSiteLocationField('nightSnackPhoto'),
                ])->values()->toArray()

        ]);
        return $result;
    }


    /**
     * 客流预估
     *
     * @param OpenShopSiteLocationModel $openShopSiteLocationModel
     * @return array
     */
    public static function getEstimationCustomerElement(OpenShopSiteLocationModel $openShopSiteLocationModel): array
    {
        //获取店铺类型
        $type = $openShopSiteLocationModel->siteType ?: 0;
        if (in_array($type, [
            SiteLocationEnum::SITE_TYPE_1,
            SiteLocationEnum::SITE_TYPE_2,
            SiteLocationEnum::SITE_TYPE_3,
            SiteLocationEnum::SITE_TYPE_4,
            SiteLocationEnum::SITE_TYPE_15,
            SiteLocationEnum::SITE_TYPE_18
        ])) {
            $labelWeek = 'marketWeek';  // 根据数据库config配置
            $labelDay  = 'marketDay';  // 根据数据库config配置
            $divisor1  = 0.219386210321065; // 默认除数
            $divisor2  = 0.198127336238839; // 默认除数
        } else {
            $labelWeek = 'streetWeek';  // 根据数据库config配置
            $labelDay  = 'streetDay';  // 根据数据库config配置
            $divisor1  = 0.145220082530949; // 默认除数
            $divisor2  = 0.120094572410874; // 默认除数
        }

        //获取算法类型
        ConfigModel::query()
                   ->where('module', 'siteLocation')
                   ->whereIn('name', [$labelWeek, $labelDay])
                   ->get()
                   ->each(function ($item) use ($labelWeek, $labelDay, &$algorithmWeek, &$algorithmDay) {
                       if ($item->name == $labelWeek) {
                           $algorithmWeek = json_decode($item->value);
                       }
                       if ($item->name == $labelDay) {
                           $algorithmDay = json_decode($item->value);
                       }
                   });

        $weekTotalArr = [];
        $weekDayArr   = [];
        foreach ($openShopSiteLocationModel->customerAnalysisRel as $customerAnalysis) {
            if (!isset($customerAnalysis->id)) {
                continue;
            }
            $weekDay = (string)($customerAnalysis->week % 7);
            //目前涉及到的有 afternoonNumber  afternoonTeaNumber  nightNumber nightSnackNumber  分别对应键值对  4 5 6 7
            $formula = $algorithmWeek->$weekDay;
            if ($customerAnalysis->afternoonNumber) {
                //一周总客流预测
                $weekDayTotal1  = (int)($customerAnalysis->afternoonNumber / ($formula[4]->divisor1 ?: $divisor1) / ($formula[4]->divisor2 ?: $divisor2));
                $weekDayArr[]   = collect($algorithmDay)->map(function ($v) use ($weekDayTotal1) {
                    return (int)($weekDayTotal1 * $v);
                })->toArray();
                $weekTotalArr[] = ['res' => $weekDayTotal1];
            }
            if ($customerAnalysis->afternoonTeaNumber) {
                //一周总客流预测
                $weekDayTotal2  = (int)($customerAnalysis->afternoonTeaNumber / ($formula[5]->divisor1 ?: $divisor1) / ($formula[5]->divisor2 ?: $divisor2));
                $weekDayArr[]   = collect($algorithmDay)->map(function ($v) use ($weekDayTotal2) {
                    return (int)($weekDayTotal2 * $v);
                })->toArray();
                $weekTotalArr[] = ['res' => $weekDayTotal2];
            }
            if ($customerAnalysis->nightNumber) {
                //一周总客流预测
                $weekDayTotal3  = (int)($customerAnalysis->nightNumber / ($formula[6]->divisor1 ?: $divisor1) / ($formula[6]->divisor2 ?: $divisor2));
                $weekDayArr[]   = collect($algorithmDay)->map(function ($v) use ($weekDayTotal3) {
                    return (int)($weekDayTotal3 * $v);
                })->toArray();
                $weekTotalArr[] = ['res' => $weekDayTotal3];
            }
            if ($customerAnalysis->nightSnackNumber) {
                //一周总客流预测
                $weekDayTotal4  = (int)($customerAnalysis->nightSnackNumber / ($formula[7]->divisor1 ?: $divisor1) / ($formula[7]->divisor2 ?: $divisor2));
                $weekDayArr[]   = collect($algorithmDay)->map(function ($v) use ($weekDayTotal4) {
                    return (int)($weekDayTotal4 * $v);
                })->toArray();
                $weekTotalArr[] = ['res' => $weekDayTotal4];
            }
        }
        return [
            'customWeekTotal'     => (int)collect($weekTotalArr)->average('res'),
            'customMonthTotal'    => (int)(collect($weekTotalArr)->average('res') * 4),
            'chart'               => [
                'name' => '星期客流',
                'data' => [
                    (int)(collect($weekDayArr)->average('0')),
                    (int)(collect($weekDayArr)->average('1')),
                    (int)(collect($weekDayArr)->average('2')),
                    (int)(collect($weekDayArr)->average('3')),
                    (int)(collect($weekDayArr)->average('4')),
                    (int)(collect($weekDayArr)->average('5')),
                    (int)(collect($weekDayArr)->average('6')),
                ]
            ],
            'estimationOrder'     => '25元/单(点单)',
            'MonthOrderGMV'       => round(collect($weekTotalArr)->average('res') * 4 * 25, 2),
            'estimationChooseOwn' => '30元/单(自选)',
            'MonthChooseOwnGMV'   => round(collect($weekTotalArr)->average('res') * 4 * 30, 2),
        ];
    }

    /**
     * @param int $position
     * @param int $businessId
     * @return array
     */
    public static function getFieldResource(int $position, int $businessId): array
    {
        if (SiteLocationService::$siteLocationModel->attachRel) {
            $attachFile = SiteLocationService::$siteLocationModel->attachRel->where("position", $position)
                                                                            ->where('businessId', $businessId);
            if ($attachFile) {
                return $attachFile
                    ->pluck("url")
                    ->map(
                        $attachFile->getIterator()->current()->isPublic ? "picturePath" : "privateFilePath"
                    )->toArray();
            }

        }
        return [];
    }

    /**
     * 竞品/互补品
     *
     * @param int $type
     * @return array
     */
    public static function getProductElement(int $type): array
    {
        if (
            self::$siteLocationModel->productAnalysisRel
            &&
            $product = self::$siteLocationModel->productAnalysisRel->where("type", $type)
        ) {
            $existsEatInGraduationReceiptPhoto = false;
            if (
                SiteLocationService::$siteLocationModel->attachRel->isNotEmpty()
                &&
                SiteLocationService::$siteLocationModel->attachRel
                    ->where("position", UploadFileResourceEnum::PRODUCT_EAT_IN_GRADUATION_RECEIPT_PHOTO)
                    ->whereIn('businessId', $product->pluck("id"))
                    ->count() > 0
            ) {
                $existsEatInGraduationReceiptPhoto = true;
            }
            $product = $product->map(function ($p) use ($existsEatInGraduationReceiptPhoto) {
                $customerEnum = new SiteLocationFormEnum(
                    collect(array_merge($p->toArray(),
                        ["existsEatInGraduationReceiptPhoto" => $existsEatInGraduationReceiptPhoto])),
                    self::$siteLocationModel->source
                );
                return [
                    'name'       => $p->productName,
                    "isTemplate" => false,
                    'id'         => $p->id,
                    'tab1'       => [
                        $customerEnum->getSiteLocationField('productName' . $p->type),
                        $customerEnum->getSiteLocationField(
                            'shopInnerPhoto', "", $p->id
                        ),
                        $customerEnum->getSiteLocationField(
                            'eatInGraduationReceiptPhoto',
                            "",
                            $p->id
                        ),
                        // 门店图片
                        $customerEnum->getSiteLocationField(
                            'dazhongPhoto', "", $p->id
                        ),
                        // 大众点评
                        $customerEnum->getSiteLocationField('elemNumber' . $p->type),
                        // 饿了么客单量
                        $customerEnum->getSiteLocationField('elemUnitPrice' . $p->type),
                        // 饿了么客单价
                        $customerEnum->getSiteLocationField(
                            'elemPhoto', "", $p->id
                        ),
                        // 饿了么
                        $customerEnum->getSiteLocationField('meituanNumber' . $p->type),
                        // 饿了么客单量
                        $customerEnum->getSiteLocationField('meituanUnitPrice' . $p->type),
                        // 饿了么客单量
                        $customerEnum->getSiteLocationField('meituanPhoto', "", $p->id),
                        // 美团
                        $customerEnum->getSiteLocationField('specialExplanation')
                    ]
                ];
            })->values()->toArray();
        } else {
            $product = [];
        }

        $customerEnum = new SiteLocationFormEnum(collect(), self::$siteLocationModel->source);
        array_push($product, [
            'name'       => "",
            "isTemplate" => true,
            'tab1'       => [
                $customerEnum->getSiteLocationField('productName' . $type),
                $customerEnum->getSiteLocationField('shopInnerPhoto'),
                $customerEnum->getSiteLocationField('eatInGraduationReceiptPhoto'),
                // 门店图片
                $customerEnum->getSiteLocationField('dazhongPhoto'),
                // 大众点评
                $customerEnum->getSiteLocationField('elemNumber' . $type),
                // 饿了么客单量
                $customerEnum->getSiteLocationField('elemUnitPrice' . $type),
                // 饿了么客单价
                $customerEnum->getSiteLocationField('elemPhoto'),
                // 饿了么
                $customerEnum->getSiteLocationField('meituanNumber' . $type),
                // 饿了么客单量
                $customerEnum->getSiteLocationField('meituanUnitPrice' . $type),
                // 饿了么客单量
                $customerEnum->getSiteLocationField('meituanPhoto'),
                // 美团
                $customerEnum->getSiteLocationField('specialExplanation')
            ]
        ]);

        return $product;

//        $product->push(collect(['type' => $type]));
//        foreach ($product as $customer) {
//            if ($type != ($customer['type'])) {
//                continue;
//            }
//            $customerEnum = new SiteLocationFormEnum($customer->toArray(), $source);
//            $data         = [
//                'name' => $customer['productName'] ?? '',
//                'id'   => $customer['id'] ?? 0, // 前段要求 如果为 0 删除 id 这个字段
//                'tab1' => [
//                    $customerEnum->getSiteLocationField('productName' . $type),
//                    // 名字
//                    $customerEnum->getSiteLocationField(
//                        'shopInnerPhoto',
//                        $customer['fileList']['shopInnerPhoto'] ?? []
//                    ),
//                    $customerEnum->getSiteLocationField('eatInGraduationReceiptPhoto',
//                        $customer['fileList']['eatInGraduationReceiptPhoto'] ?? []),
//                    // 门店图片
//                    $customerEnum->getSiteLocationField('dazhongPhoto', $customer['fileList']['dazhongPhoto'] ?? []),
//                    // 大众点评
//                    $customerEnum->getSiteLocationField('elemNumber' . $type),
//                    // 饿了么客单量
//                    $customerEnum->getSiteLocationField('elemUnitPrice' . $type),
//                    // 饿了么客单价
//                    $customerEnum->getSiteLocationField('elemPhoto', $customer['fileList']['elemPhoto'] ?? []),
//                    // 饿了么
//                    $customerEnum->getSiteLocationField('meituanNumber' . $type),
//                    // 饿了么客单量
//                    $customerEnum->getSiteLocationField('meituanUnitPrice' . $type),
//                    // 饿了么客单量
//                    $customerEnum->getSiteLocationField('meituanPhoto', $customer['fileList']['meituanPhoto'] ?? []),
//                    // 美团
//                    $customerEnum->getSiteLocationField('specialExplanation')
//                ]
//            ];
//
//            if ($data['id'] === 0) {
//                unset($data['id']);
//            }
//            $tab[] = $data;
//        }
//        return $tab;
    }

    public static function houseClueFilterField($siteLocationEnum)
    {
        $siteLocationEnum::setCustomerField([
            'productName'                 => [
                'required' => false,
            ],
            'productName1'                => [
                'required' => false,
            ],
            'productName2'                => [
                'required' => false,
            ],
            'shopInnerPhoto'              => [
                'required' => false,
            ],
            'dateType'                    => [
                'required' => false,
            ],
            'weather'                     => [
                'required' => false,
            ],
            'waterFeeMonth'               => [
                'required' => false,
            ],
            'electricityFeeMonth'         => [
                'required' => false,
            ],
            'shopManagerCount'            => [
                'required' => false,
            ],
            'shopManagerMonthSalary'      => [
                'required' => false,
            ],
            'shopAssistantCount'          => [
                'required' => false,
            ],
            'shopAssistantMonthSalary'    => [
                'required' => false,
            ],
            'customerUnitPriceEstimation' => [
                'required' => false,
            ]

        ]);
    }


    /**
     * @param string|null $field
     * @return array
     * @throws GuzzleException
     */
    public static function templateElement(?string $field = ''): array
    {
        $nearbyShopName = '-';
        // try {
        //     GuanyuanDataService::setTimeOut(20);
        //     $shopInfo = self::$siteLocationModel->nearbyShopCode ? (GuanyuanDataService::newShopList(self::$siteLocationModel->nearbyShopCode)[0] ?? []) : [];
        // } catch (\Exception $exception) {
        //     $shopInfo = [];
        // }
        // if (!empty($shopInfo)) $nearbyShopName = '【' . ($shopInfo['状态'] ?? '-') . '】'. ($shopInfo['门店名称'] ?? '-');

//        dd(self::$siteLocationModel->source);

        if ($nearbyShopName == '-') {
            try {
                $nearbyShopName = self::$siteLocationModel->nearbyShopCode . ShopService::getShopNameByCode(self::$siteLocationModel->nearbyShopCode);
            } catch (\Exception $exception) {}
        }
        //规避附近门店为0情况
        if (self::$siteLocationModel->nearbyShopCode == 0) {
            $nearbyShopName = '该城市内无附近门店';
        }

        self::$siteLocationFormEnum = new SiteLocationFormEnum(
            collect(array_merge(self::$siteLocationModel->toArray(), ['nearbyShopName' => $nearbyShopName])),
            self::$siteLocationModel->source
        );

        $lists = self::getFormContent();
        //判断来源
        //选址1.1.2优化 去掉门店名称
        //        if (self::$siteLocationModel->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP) {
        //            // 获取门店名称
        //            $notice = new NoticeService(self::$siteLocationModel->orderNo);
        //            $notice = $notice->getShopName();
        //        } else {
        //            self::houseClueFilterField(self::$siteLocationFormEnum);
        //            $notice = '';
        //        }

        $res = [];
        foreach ($lists as $elements) {
            $res[] = $elements;
        }

        if (!empty($field)) {
            $filterArr = array_column($res, null, 'key');
            return $filterArr[$field];
        }

        return $res;
    }

    /**
     * @return array[]
     * @throws GuzzleException
     * @throws Exception
     */
    public static function getFormContent(): array
    {
        if (self::$siteLocationModel->getAttribute("isSolicitBusinessManager")) {
            //招商精简表单
            return [
                self::initItemInfo(),
                self::initGeneratrixInfo(),
                self::initLocationsPhoto(),
                self::initEngineeringCondition(),
                self::initBusinessConditions(),
                self::initProjectSummary()
            ];
        } else {
            //完整表单
            $lists = [
                self::initItemInfo(),
                self::initGeneratrixInfo(),
                self::initLocationsPhoto(),
                self::initOperatingState(),
                //self::initCustomers()  客群分析
            ];
            //if (!(in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL]) && self::$siteLocationModel->openingStatus == SiteLocationEnum::OPENING_STATUS_OFF)) {
            //    array_push($lists, self::initCompetingGoods(), self::initComplementary());
            //}
            array_push(
                $lists, self::initCompetingGoods(), self::initComplementary(),
                self::takeOutEstimate(),
                self::initEngineeringCondition(),
                self::initBusinessConditions(),
                //self::initCapitalBudgeting(),
                self::initCapitalBudgetingV2(),
                self::initProjectSummary()
            );
            return $lists;
        }
    }

    /**
     * @return array
     */
    public static function initItemInfo(): array
    {
        if (self::$siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4) {
            $nearbyPlaceHolderName = OpenShopSiteLocationModel::getShopNameByIdNearByPlaceholderId(self::$siteLocationModel->nearbyPlaceHolderId);
        } else {
            $nearbyPlaceHolderName = AreaService::getAreaCodeByArea(self::$siteLocationModel->longitude,
                    self::$siteLocationModel->latitude)['nearbyPlaceHolderName'] ?? '';
        }

        if (self::$siteLocationModel->townGrade) {
            $town = self::$siteLocationModel->town . '（' . (ProgrammingEnum::GRADE_MAPPING[self::$siteLocationModel->townGrade] ?? '-') . '）';
        } else {
            $town = self::$siteLocationModel->town ?: '-';
        }

        return [
            'sort'  => 0,
            'key'   => 'itemInfo',
            'name'  => '项目信息',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('shopType'), // 店型
                        self::getSiteLocationField('siteSelection'), // 选址场景
                        self::getSiteLocationField('recommendType'), // 选址场景
                        self::getSiteLocationField('messageFrom'), // 门店信息
                        self::getSiteLocationField('longitude'), // 门店经度
                        self::getSiteLocationField('latitude'), // 门店纬度
                        self::getSiteLocationField('siteAddress'), // 经纬度地址
                        self::getSiteLocationField('nearbyShopName'), // 附近门店
                        self::getSiteLocationField('nearbyShopCode'), // 附近门店
                        self::getSiteLocationField('nearbyRange'), // 附近门店距离

                        self::getSiteLocationField('nearbyPlaceHolderName', $nearbyPlaceHolderName), // 附近点位
                        self::getSiteLocationField('nearbyPlaceHolderRange'), // 附近点位距离

                        self::getSiteLocationField('cityArea'), // 门店城市
                        self::getSiteLocationField('town', $town), // 乡镇街道
                        self::getSiteLocationField('cityType'), // 门店城市等级
                        self::getSiteLocationField('address'), // 门店地址
                        //self::getSiteLocationField("shopName", $notice), // 门店名称 选址1.1.2优化  去掉门店名称
                        self::getSiteLocationField("shopName"), // 门店名称
                        self::getSiteLocationField("selectTime", self::$siteLocationModel->selectTime > 0 ?
                            date('Y-m-d', self::$siteLocationModel->selectTime) : ''), // 选址时间
                        self::getSiteLocationField("heatMap"), // 百度热力图
                    ]
                ]

            ]
        ];
    }

    /**
     * 门店介绍
     *
     * @return array
     */
    public static function initLocationsPhoto(): array
    {
        if (in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET])) {
            $tips = ['优先选择SAB级商场落位，房租整体控制在30,000以内，店宽底线为 3m，最佳 4m 以上，面积最好在40-60㎡'];
        } else {
            $cityType = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[self::$siteLocationModel->cityType] ?? '五线';
            $rent     = SiteLocationEnum::CITY_TYPE_LEVEL_RENT_TIPS_TEXT[self::$siteLocationModel->cityType] ?? '5000元左右';
            $area     = SiteLocationEnum::CITY_TYPE_LEVEL_AREA_TIPS_TEXT[self::$siteLocationModel->cityType] ?? '50-80㎡';
            $tips = [
                "1、房租：{$cityType}城市街边店房租建议控制在{$rent}",
                "2、展面: 双展面金角>单展面>亭子",
                "3、面积: {$cityType}城市面积可控制在{$area}",
            ];
        }
        $mallSource = false;

        if (SiteLocationService::$siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
            $mallSource = MallSettleInShopInfoModel::query()->where('mallId', SiteLocationService::$siteLocationModel->mallId)->count();
            if (SiteLocationService::$siteLocationModel->blongFloor != '金街') {
                $recommendFloor = SiteLocationMallModel::getRecommendFloorInfo((string)SiteLocationService::$siteLocationModel->mallId);
            }
        }

//        $thisFloorStore = [];
//        if (mb_strlen(SiteLocationService::$siteLocationModel->blongFloor)) {
//            $thisFloorStore = MallSettleInShopInfoModel::getStoreByMallIdANDFloor(SiteLocationService::$siteLocationModel->mallId, SiteLocationService::$siteLocationModel->blongFloor);
//        }
        $pushArr = [];

        //前提是商场店
        //有楼层信息，并且有推荐楼层，展示推荐楼层   反之 没有推荐楼层
        if (SiteLocationService::$siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
            $pushArr[] = self::getSiteLocationField('belongFloor', SiteLocationService::$siteLocationModel->blongFloor);
            if ($mallSource && mb_strlen($recommendFloor['recommendFloor'] ?? '')) {
                $pushArr[] = self::getSiteLocationField('recommendFloor', $recommendFloor['recommendFloor']);   //推荐楼层
            }
        }


        return [
            'sort'  => 10,
            'tips'  => $tips,
            'key'   => 'locationsPhoto',
            'name'  => '门店介绍',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => array_merge([
                        //movingLineExplanationVideo
                        self::getSiteLocationField('shopModelType'), // 门店信息
                        self::getSiteLocationField('shopType'), // 店型
                        self::getSiteLocationField('posLine', ''), // 点餐动线
                        self::getSiteLocationField('siteSelection'), // 选址场景
                        self::getSiteLocationField('openingStatus'), // 商场开业状态
                    ], $pushArr, [
                        self::getSiteLocationField('shopVideo'),
                        self::getSiteLocationField('floorExplanationVideo'),
                        self::getSiteLocationField('peripheralVideo'),
                        self::getSiteLocationField('shopInVideo'),
                        //                        self::getSiteLocationField('shopVideo', $file['shopVideo']), // 视频
                        self::getSiteLocationField('leftPhoto'), // 左视图
                        self::getSiteLocationField('frontPhoto'), // 正视图
                        self::getSiteLocationField('rightPhoto'), // 右视图
                        self::getSiteLocationField('innerPhoto'), // 店内
                        self::getSiteLocationField('panoramaPhoto'), // 远景图
                    ])
                ]
            ]
        ];
    }

    /**
     * 经营状态
     *
     * @return array
     */
    public static function initOperatingState(): array
    {
        return [
            'sort'  => 20,
            'key'   => 'operatingState',
            'name'  => '经营状态',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('currentFormat', ""),  // 当前业态
                        self::getSiteLocationField('operatingStatus', ""), // 当前经营状态
                        self::getSiteLocationField('leaseStatus', ""), // 当前租赁状态
                        self::getSiteLocationField('driveType', ""), // 客流驱动类型
                    ]
                ],
                'tab2' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('siteType', ""), // 店址类型
                    ]
                ]
            ]
        ];
    }

    /**
     * 外卖预估
     *
     * @return array
     * @throws Exception
     */
    public static function takeOutEstimate(): array
    {
        $lng = self::$siteLocationModel->longitude;
        $lat = self::$siteLocationModel->latitude;
        $distance = 3;  //默认3km
        // 外卖预估数据
        if (!$lng || !$lat) {
            $elmSalesVolume = $takeOutDoubleSalesVolume = $takeOutDoubleSalesVolumeReceived = $mtSalesVolume = '';
            $kfSalesVolume  = $mtFriedGoods = $elmFriedGoods = [];
        } else {
            $takeOutData = (new WaiMaiAnalysisService())
                ->setLngLat($lng, $lat, $distance);

            $estimate = $takeOutData->calcEstimateData();

            $takeOutDoubleSalesVolume         = (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2);
            $takeOutDoubleSalesVolumeReceived = ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30);
            $mtSalesVolume                    = (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2);
            $elmSalesVolume                   = (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2);

            // 夸父门店TOP3
            $kfSalesVolume = collect($takeOutData->getNearByKfShops(3))->map(function ($item) {
                return [
                    'shopName' => $item->shopName,
                    'distance' => round($item->distance, 2) . 'km',
                    'mtElm'    => $item->mt . ' / ' . $item->elm . ' / ' . ($item->mt + $item->elm),
                ];
            })->values()->toArray();

            // 炸串炸鸡美团TOP5
            $mtFriedGoods = $takeOutData->getNearBySourceTypeRank(RmsShopApi::SOURCE_TYPE_WM_MT, WaiMaiAnalysisModel::CATEGORY_TYPE_FRIED, false, 5)->map(function ($item) {
                return [
                    'shopName' => $item['shopName'],
                    'distance' => round($item['distance'], 2) . 'km',
                    'mt'       => $item['orderNum'],
                ];
            })->values()->toArray();
            if (count($mtFriedGoods)) {
                $mtFriedGoods[] = [
                    'shopName' => '平均单量',
                    'distance' => '',
                    'mt'       => (int)collect($mtFriedGoods)->avg('mt'),
                ];
            }


            // 炸串炸鸡饿了么TOP5
            $elmFriedGoods = $takeOutData->getNearBySourceTypeRank(RmsShopApi::SOURCE_TYPE_WM_ELM, WaiMaiAnalysisModel::CATEGORY_TYPE_FRIED, false, 5)->map(function ($item) {
                return [
                    'shopName' => $item['shopName'],
                    'distance' => round($item['distance'], 2) . 'km',
                    'elm'      => $item['orderNum'],
                ];
            })->values()->toArray();
            if (count($elmFriedGoods)) {
                $elmFriedGoods[] = [
                    'shopName' => '平均单量',
                    'distance' => '',
                    'elm'       => (int)collect($elmFriedGoods)->avg('elm'),
                ];
            }
        }

        //地图图片
        $heatmap = self::getHeatMap();

        return [
            'sort'  => 65,
            'key'   => 'takeOutEstimate',
            'name'  => '外卖预估',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'title'  => '外卖月销预估',
                    'value'  => [
                        self::getSiteLocationField('wmHeatMap', $heatmap),  // 热力图
                        self::getSiteLocationField('takeOutDoubleSalesVolume', $takeOutDoubleSalesVolume),                                                     // 双平台外卖月销量预估
                        self::getSiteLocationField('takeOutDoubleSalesVolumeReceived', $takeOutDoubleSalesVolumeReceived),                                     // 双平台外卖实收预估
                        self::getSiteLocationField('mtSalesVolume', $mtSalesVolume),                                                                           // 美团外卖月销量预估
                        self::getSiteLocationField('elmSalesVolume', $elmSalesVolume), // 饿了么外卖月销量预估
                    ]
                ],
                'tab2' => [
                    'parent' => '',
                    'title'  => '夸父门店外卖月销量Top3',
                    'value'  => [
                        self::getSiteLocationField('kfSalesVolume', $kfSalesVolume),
                    ]
                ],
                'tab3' => [
                    'parent' => '',
                    'title'  => '炸串炸鸡美团外卖月销量Top5',
                    'value'  => [
                        self::getSiteLocationField('mtFriedGoods', $mtFriedGoods),
                    ]
                ],
                'tab4' => [
                    'parent' => '',
                    'title'  => '炸串炸鸡饿了么外卖月销量Top5',
                    'value'  => [
                        self::getSiteLocationField('elmFriedGoods', $elmFriedGoods),
                    ]
                ]
            ]
        ];
    }

    /**
     * 动线说明
     *
     * @return array
     */
    public static function initGeneratrixInfo(): array
    {
        return [
            'sort'  => 5,
            'key'   => 'generatrixInfo',
            'name'  => '动线说明',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('lineMarking'), // 动线标注
                        self::getSiteLocationField('flowLine', ""), //  人流动线
                        self::getSiteLocationField('orientation', ""), // 朝向
                        self::getSiteLocationField('yinYangJie', ""), // 阴阳街
                        self::getSiteLocationField('visualLabel', ""), // 可视性标签
                        self::getSiteLocationField('streetLength', ""), // 商业街长度
                    ]
                ]
            ]
        ];
    }

    /**
     * 客群分析
     *
     * @return array
     */
    public static function initCustomers(): array
    {
        return [
            'sort'  => 40,
            'key'   => 'customers',
            'name'  => '客群分析',
            'value' => self::getCustomerElement(self::$siteLocationModel)
        ];
    }

    /**
     * 竞品分析
     *
     * @return array
     */
    public static function initCompetingGoods(): array
    {
        $configJson  = ConfigModel::query()
            ->where('module', 'wanggui')
            ->where('name', 'competingGoods')
            ->value('value');
        $config      = json_decode($configJson, true)[0];
        $shopMallRes = false;
        $explain     = [];
        if (in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET])) {
            $shopMallRes = true;
        }
        foreach ($config['conditions'] as $value) {
            if ($value['condition']['shopModelType'] == $shopMallRes && $value['condition']['cityGrade'] == self::$siteLocationModel->cityType) {
                $explain   = $value['explain'];
                break;
            }
        }
        return [
            'sort'      => 50,
            'tips'      => $explain,
            'key'       => 'competingGoods',
            'name'      => '竞品分析',
            'value'     => self::getProductElement(1)
        ];
    }

    /**
     * 互补品
     *
     * @return array
     */
    public static function initComplementary(): array
    {
        $configJson  = ConfigModel::query()
            ->where('module', 'wanggui')
            ->where('name', 'complementary')
            ->value('value');
        $config      = json_decode($configJson, true)[0];
        $shopMallRes = false;
        $explain     = [];
        if (in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET])) {
            $shopMallRes = true;
        }
        foreach ($config['conditions'] as $value) {
            if ($value['condition']['shopModelType'] == $shopMallRes && $value['condition']['cityGrade'] == self::$siteLocationModel->cityType) {
                $explain   = $value['explain'];
                break;
            }
        }
        return [
            'sort'  => 60,
            'tips'  => $explain,
            'key'   => 'complementary',
            'name'  => '互补品分析',
            'value' => self::getProductElement(2)
        ];
    }

    /**
     * 工程条件
     *
     * @return array
     */
    public static function initEngineeringCondition(): array
    {
        return [
            'sort'  => 70,
            'tips'  =>  [
                '炸鸡饮品工程条件推荐：',
                '炸串+炸鸡+饮品：面积 ≥ 30㎡，电量 ≥ 35kw，双展面或展面 ≥ 3.6m',
                '炸串+炸鸡：面积 ≥ 15㎡，电量 ≥ 30kw，双展面或展面 ≥ 3.6m',
                '炸串+饮品：面积 ≥ 15㎡，电量 ≥ 30kw，双展面或展面 ≥ 3.6m',
                '收银台面积≥1.3m宽度（必要条件）',
            ],
            'key'   => 'engineeringCondition',
            'name'  => '工程条件',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('decorationShopType', ""),
                        // 装修店型
                        self::getSiteLocationField('doorWidth', ""),
                        // 门宽度
                        self::getSiteLocationField('doorHeadWidth', ""),
                        // 门头牌匾横向长度
                        self::getSiteLocationField('shopWidth', ""),
                        // 店宽
                        self::getSiteLocationField('floorHeight', ""),
                        // 层高
                        self::getSiteLocationField('depth', ""),
                        // 进深
                        self::getSiteLocationField('doorDepthWidthPhoto'),
                        // 进深
                        self::getSiteLocationField('area', ""),
                        // 面积

                        self::getSiteLocationField('openDoorType', ""),  // 铺位开门形式
                        self::getSiteLocationField('isChangeDoor', ""),  // 是否可改为玻璃开门

                        self::getSiteLocationField('wallTileUsedOld', ""),
                        // 地砖墙砖是否利旧
                        self::getSiteLocationField('wallTileUsedOldPhoto'),
                        // 地砖墙砖是否利旧图片
                        self::getSiteLocationField('isCapacityIncrease', ""),
                        // 用电量
                        self::getSiteLocationField('electricityConsumption', ""),
                        // 用电量
                        self::getSiteLocationField('capacityIncreaseFee', ""),
                        // 电量增容
                        self::getSiteLocationField('exhaustAirVolume', ""),
                        // 排风量
                        self::getSiteLocationField('isExhaustReconstruction', ""),
                        // 排风改造
                        self::getSiteLocationField('upperWaterDiameter', ""),
                        // 上水管径
                        self::getSiteLocationField('lowerWaterDiameter', ""),
                        // 下水管径
                        self::getSiteLocationField('isReformWater', ""),
                        // 水管改造
                        self::getSiteLocationField('airConditionerCType', ""),
                        // 空调
                        self::getSiteLocationField('isFireControl', ""),
                        // 消防
                        self::getSiteLocationField('adSpaceNumber', ""),
                        // 广告位
                    ]
                ]
            ]
        ];
    }

    /**
     * 商务条件
     *
     * @return array
     */
    public static function initBusinessConditions(): array
    {
        if (in_array(self::$siteLocationModel->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET])) {
            $mallGrade = (self::$siteLocationModel->mallGrade == '未评级' || empty(self::$siteLocationModel->mallGrade)) ? 'C级' : self::$siteLocationModel->mallGrade;
            $rentMall  = ProgrammingEnum::GRADE_RENT_MAPPING[self::$siteLocationModel->mallGrade] ?? '老的尽量不落位，新开商业15K左右';
            $areaMall  = ProgrammingEnum::GRADE_AREA_MAPPING[self::$siteLocationModel->mallGrade] ?? '40-50㎡';
            $tips = [
                "{$mallGrade}商场，{$rentMall}",
                "店宽区间建议：底线位3m，最佳4m以上",
                "面积区间建议：{$areaMall}"
            ];
        } else {
            $cityType = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[self::$siteLocationModel->cityType] ?? '五线';
            $rent     = SiteLocationEnum::CITY_TYPE_LEVEL_RENT_TIPS_TEXT[self::$siteLocationModel->cityType] ?? '5000元左右';
            $area     = SiteLocationEnum::CITY_TYPE_LEVEL_AREA_TIPS_TEXT[self::$siteLocationModel->cityType] ?? '50-80㎡';
            $tips = [
                "1、房租：{$cityType}城市街边店房租建议控制在{$rent}",
                "2、展面: 双展面金角>单展面>亭子",
                "3、面积: {$cityType}城市面积可控制在{$area}",
            ];
        }
        return [
            'sort'  => 80,
            'tips'  => $tips,
            'key'   => 'businessConditions',
            'name'  => '商务条件',
            'value' => [
                'tab1' => [
                    'title'  => '商铺租赁信息',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('rentType'), // 计租方式
                        self::getSiteLocationField('fixedRent'), // 固定租金
                        self::getSiteLocationField('remind'),// 提点百分比
                        self::getSiteLocationField('rentPaymentCycle'), // 租金支付周期
                        self::getSiteLocationField('deposit'), // 押金
                        self::getSiteLocationField('leaseTerm'), // 租金
                        self::getSiteLocationField('rentFreePeriod'), // 免租期
                    ]
                ],
                'tab2' => [
                    'title'  => '库房租赁信息',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('warehouseFixedRent'), // 年固定租金
                        self::getSiteLocationField('warehouseRentPaymentCycle'), // 租金支付周期
                        self::getSiteLocationField('warehouseDeposit'), // 押金
                        self::getSiteLocationField('warehouseLeaseTerm'), // 租期
                        self::getSiteLocationField('warehouseRentFreePeriod'), // 免租期
                    ]
                ],
                'tab3' => [
                    'title'  => '',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('caseRegisterType'), // 收银机
                        self::getSiteLocationField('cashInfoPhoto'), // 收银机说明文件
                        //self::getSiteLocationField('waterFee'), // 水费
                        //self::getSiteLocationField('electricityFee'), // 电费
                        self::getSiteLocationField('propertyFee'), // 物业费
                        self::getSiteLocationField('mobilizationMobile'), // 进场联系人
                        self::getSiteLocationField('mobilizationFee'), // 进场费
                        self::getSiteLocationField('mobilizationFeeDesc'), // 进场费说明
                        self::getSiteLocationField('transferFee'), // 转让费
                        self::getSiteLocationField('bond'), // 保证金
                        self::getSiteLocationField('manageFee'), // 管理费
                        self::getSiteLocationField('sponsorshipFee'), // 赞助费
                        self::getSiteLocationField('promotionFee'), // 推广费
                        self::getSiteLocationField('otherFee'), // 其他费用
                    ]
                ],
                'tab4' => [
                    'title'  => '门店证件办理条件',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('shopFacadeType'),
                        self::getSiteLocationField('handleBusinessLicense'),
                        // 营业执照办理
                        //self::getSiteLocationField('handleBusinessLicenseNoReason'),
                        // 不能办理原因
                        //self::getSiteLocationField('historyBusinessLicense'),
                        // 历史营业执照
                        //self::getSiteLocationField('historyBusinessLicensePhoto'),
                        // 历史营业执照照片
                        //self::getSiteLocationField('historyBusinessLicenseNoReason'),
                        // 历史营业执照无原因
                        self::getSiteLocationField('handleFoodLicense'),
                        // 食品安全许可证办理
                        //self::getSiteLocationField('handleFoodLicenseNoReason'),
                        // 不能办理原因
                        //self::getSiteLocationField('historyFoodLicense'),
                        // 历史食品安全许可证
                        //self::getSiteLocationField('historyFoodLicensePhoto'),
                        // 历史食品安全许可证照片
                        //self::getSiteLocationField('historyFoodLicenseNoReason'),
                        // 历史食品安全许可证无原因

                        self::getSiteLocationField('doubleWaimai'),
                        self::getSiteLocationField('douyin'),

                        self::getSiteLocationField('licenseRemark'),
                        // 营业执照办理

                        // 附件
                        self::getSiteLocationField('historyBusinessLicensePhoto'),

                        self::getSiteLocationField('franchiseesKnow'),

                    ]
                ],
                'tab5' => [
                    'title'  => '店面出租联系方式',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('leaseName'), // 联系方式
                        self::getSiteLocationField('leaseMobile'), // 联系人方式
                        self::getSiteLocationField('leaseWeChat'), // 联系人微信
                        self::getSiteLocationField('infoPhoto'),  // 营业资料
                    ]
                ]
            ]
        ];
    }

    /**
     * 门店成本
     *
     * @return array
     * @throws GuzzleException
     */
    public static function initCapitalBudgeting(): array
    {
        return [
            'sort'  => 85,
            'key'   => 'capitalBudgeting',
            'name'  => '门店成本',
            'value' => [
                'tab1' => [
                    'title'  => '固定成本',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('shopManagerCount'),
                        self::getSiteLocationField('shopManagerMonthSalary'),
                        self::getSiteLocationField('shopAssistantCount'),
                        self::getSiteLocationField('shopAssistantMonthSalary'),
                        self::getSiteLocationField('waterFeeMonth'),
                        self::getSiteLocationField('electricityFeeMonth'),
                        self::getSiteLocationField('rentCost',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["rentCost"]),
                        self::getSiteLocationField('expenseAllocation',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["expenseAllocation"]),
                    ]
                ],
                'tab2' => [
                    'title'  => '食材变动成本',
                    'parent' => '',
                    'value'  => [

                        self::getSiteLocationField('foodstuffMarginRate'),
                        self::getSiteLocationField('customerUnitPriceEstimation'),

                        self::getSiteLocationField('monthQuantityEstimation',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["monthQuantityEstimation"]),

                        self::getSiteLocationField('monthTurnoverEstimation',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["monthTurnoverEstimation"]),

                        self::getSiteLocationField('monthFoodstuffChangeCost',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["monthFoodstuffChangeCost"]),
                    ]
                ],
                'tab3' => [
                    'title'  => '堂食月利润预估',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('monthProfitEstimation',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["monthProfitEstimation"]),
                    ]
                ],
                'tab4' => [
                    'title'  => '堂食盈亏平衡点',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('dailyTurnover',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["dailyTurnover"]),
                        self::getSiteLocationField('dailySellAtCostOrderCount',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["dailySellAtCostOrderCount"]),
                    ]
                ],
                'tab5' => [
                    'title'  => '投资预估',
                    'parent' => '',
                    'value'  => [
                        self::getSiteLocationField('totalInvestmentEstimation',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["totalInvestmentEstimation"]),
                        self::getSiteLocationField('returnCycle',
                            self::getCapitalBudgetingPrice(self::$siteLocationModel)["returnCycle"]),
                    ]
                ]
            ]
        ];
    }


    /**
     * 投资预算
     * @return array
     */
    public static function initCapitalBudgetingV2(): array
    {
        return [
            'sort'  => 86,
            'key'   => 'capitalBudgetingV2',
            'name'  => '投资预算',
            'value' => [],
            'json'  => (new CapitalBudgetingService(self::$siteLocationModel))->json(),
            'table' => (new CapitalBudgetingService(self::$siteLocationModel))->table(),
        ];
    }

    /**
     *
     * @return array
     */
    public static function initProjectSummary(): array
    {
        return [
            'sort'  => 90,
            'key'   => 'projectSummary',
            'name'  => '项目总结',
            'value' => [
                'tab1' => [
                    'parent' => '',
                    'value'  => [

                        self::getSiteLocationField('businessStrategy', ""), // 经营策略
//                        self::getSiteLocationField('restrictedSales'), // 限制销售范围
                        self::getSiteLocationField('sellingCategory', ''), // 售卖品类
                        self::getSiteLocationField('menuLevel', ''), // 产品定价
                        self::getSiteLocationField(
                            'openTime',
                            self::$siteLocationModel->openTime > 0 ? date('Y-m-d',
                                self::$siteLocationModel->openTime) : ''
                        ), // 预计开业时间
//                        self::getSiteLocationField('shopPattern'), // 门店模式
//                        self::getSiteLocationField('patternType'), // 模式类型
                        self::getSiteLocationField('siteAdvantage'), // 店址优势
                        self::getSiteLocationField('siteInferiority'), // 店址劣势
                    ]
                ]
            ]
        ];
    }


    /**
     * 获取投资预算数据
     *
     * @param OpenShopSiteLocationModel $openShopSiteLocationModel
     * @return int[]
     * @throws GuzzleException
     */
    public static function getCapitalBudgetingPrice(OpenShopSiteLocationModel $openShopSiteLocationModel): array
    {
        $rentCost = 0;
        $rentCostShow = 0;
        switch ($openShopSiteLocationModel->siteType) {
            case SiteLocationEnum::SITE_TYPE_18:
            case SiteLocationEnum::SITE_TYPE_1:
            case SiteLocationEnum::SITE_TYPE_2:
            case SiteLocationEnum::SITE_TYPE_3:
            case SiteLocationEnum::SITE_TYPE_4:
                $a = 2;
                break;
//            case SiteLocationEnum::SITE_TYPE_5:
//            case SiteLocationEnum::SITE_TYPE_6:
//            case SiteLocationEnum::SITE_TYPE_7:
//            case SiteLocationEnum::SITE_TYPE_8:
//                $a = 1;
//                break;
            default:
                $a = 1;
                break;
        }

        $area = is_numeric($openShopSiteLocationModel->area ) ? $openShopSiteLocationModel->area : 0;
        $cityGradeInfo = RmsAreaRemote::getCityGrade($openShopSiteLocationModel->cityCode)["cityInfo"];
        $b             = $cityGradeInfo && $cityGradeInfo["grade"] ? $cityGradeInfo["grade"] : 5;

        if ($openShopSiteLocationModel->rentType == SiteLocationEnum::RENT_TYPE_1) {
            $rentCost  = $rentCostShow   = bcdiv($openShopSiteLocationModel->fixedRent, 12);
            $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100 + 2.355 * $rentCost);
        } else {
            //月营业额预估
            $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100);
            switch ($openShopSiteLocationModel->rentType) {
                case SiteLocationEnum::RENT_TYPE_2:
                    //只提点
                    //获得房租
                    $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100);
                    $tempRent = bcmul($monthTurnoverEstimation, (((int)$openShopSiteLocationModel->remind) / 100));
                    $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100 + 2.355 * $tempRent);

                    $rentCost                = bcmul($monthTurnoverEstimation,
                        (((int)$openShopSiteLocationModel->remind) / 100));

                    break;
                case SiteLocationEnum::RENT_TYPE_3:
                    $rentCost  = $rentCostShow   = bcdiv(((int)$openShopSiteLocationModel->fixedRent), 12);
                    $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100 + 2.355 * $rentCost);
//                    $rentCost_2              = bcmul($monthTurnoverEstimation,
//                        (((int)$openShopSiteLocationModel->remind) / 100));
//                    $rentCost                = $rentCost_1 + $rentCost_2;
                    break;
                case SiteLocationEnum::RENT_TYPE_4:
                    $rentCost  = $rentCostShow   = bcdiv(((int)$openShopSiteLocationModel->fixedRent), 12);
                    $monthTurnoverEstimation = (int)((50576 + 8447 * $a - 2267.6 * $b + 75.3 * $area) * 100 + 2.355 * $rentCost);
//                    $rentCost_2              = bcmul($monthTurnoverEstimation,
//                        (((int)$openShopSiteLocationModel->remind) / 100));
//                    $rentCost                = $rentCost_1 > $rentCost_2 ? $rentCost_1 : $rentCost_2;
                    break;
            }
        }

        //其他杂费
        $otherCost = bcdiv(
            //((int)$openShopSiteLocationModel->bond) +
            ((int)$openShopSiteLocationModel->manageFee) +
            ((int)$openShopSiteLocationModel->sponsorshipFee) +
            ((int)$openShopSiteLocationModel->promotionFee) +
            ((int)$openShopSiteLocationModel->otherFee) +
            ((int)$openShopSiteLocationModel->propertyFee) +
            ((int)$openShopSiteLocationModel->mobilizationFee),
            12) * 100;

        //总投资预算其他杂费
        $otherCost1 = bcdiv(
            ((int)$openShopSiteLocationModel->manageFee) +
            ((int)$openShopSiteLocationModel->propertyFee),
            12) * 100;



        $onlyRentCost = $rentCost;
        $rentCost     = $rentCost + $otherCost;


        //费用分摊
        $expenseAllocation = (int)(($openShopSiteLocationModel->userContractRel ? (
                bcdiv(((int)$openShopSiteLocationModel->userContractRel->technologyTransferFee), 36) +
                bcdiv(((int)$openShopSiteLocationModel->userContractRel->managementCost), 12) +
                bcdiv(((int)$openShopSiteLocationModel->userContractRel->initialFee), 36)
            ) : 0)
            + 16700 + 138800 + (int)(($area * 2500 * 100) / 24));

        $fixedCost = function (OpenShopSiteLocationModel $openShopSiteLocationModel, $rentCost, $expenseAllocation) {
            return ((int)$openShopSiteLocationModel->shopManagerCount) * ((int)$openShopSiteLocationModel->shopManagerMonthSalary) +
                ((int)$openShopSiteLocationModel->shopAssistantCount) * ((int)$openShopSiteLocationModel->shopAssistantMonthSalary) +
                ((int)$openShopSiteLocationModel->electricityFeeMonth) + ((int)$openShopSiteLocationModel->waterFeeMonth) +
                $rentCost + $expenseAllocation;
        };

        switch ($openShopSiteLocationModel->rentPaymentCycle) {
            case SiteLocationEnum::RENT_PAYMENT_CYCLE_1:
                $payMonth = 12;
                break;
            case SiteLocationEnum::RENT_PAYMENT_CYCLE_2:
                $payMonth = 4;
                break;
            case SiteLocationEnum::RENT_PAYMENT_CYCLE_3:
                $payMonth = 2;
                break;
            case SiteLocationEnum::RENT_PAYMENT_CYCLE_4:
                $payMonth = 1;
                break;
            default:
                $payMonth = 0;
                break;
        }

        //$decorationCost = $area * 2500 * 100;

        //修改固定逻辑
        $decorationCost = 47012.36 + (132.83 * $area) + (((int)($payMonth == 0 || $openShopSiteLocationModel->rentType == SiteLocationEnum::RENT_TYPE_2 ? 0 : ((int)$openShopSiteLocationModel->fixedRent) / 12 / 100)) * 0.75) + (SiteLocationEnum::CITY_TYPE_LEVEL_DECORATION_COST[(int)$openShopSiteLocationModel->cityType] ?? 0) + (in_array($openShopSiteLocationModel->shopModelType,[SiteLocationEnum::SHOP_MODEL_TYPE_MALL, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_INSIDE, SiteLocationEnum::SHOP_MODEL_TYPE_MALL_STREET]) ? +2884.61 : -2884.61);
        $decorationCost = $decorationCost * 100;
        $totalInvestmentEstimation =
            (int)($payMonth == 0 || $openShopSiteLocationModel->rentType == SiteLocationEnum::RENT_TYPE_2 ? 0 : ((int)$openShopSiteLocationModel->fixedRent) / $payMonth) +
            $otherCost1 * 12 +
            //((int)$openShopSiteLocationModel->deposit * 100) +  押金不计算在内
            (int)(($openShopSiteLocationModel->userContractRel ? (
                (int)$openShopSiteLocationModel->signOrderRel->shouldPayPrice
//                    ((int)$openShopSiteLocationModel->userContractRel->decorationDeposit) +
//                    ((int)$openShopSiteLocationModel->userContractRel->deposit) +
//                    ((int)$openShopSiteLocationModel->userContractRel->technologyTransferFee) +
//                    ((int)$openShopSiteLocationModel->userContractRel->managementCost) +
//                    ((int)$openShopSiteLocationModel->userContractRel->initialFee)
                ) : 0) + 6000 * 100 + 50000 * 100 + 30000 * 100 + $decorationCost
                //+ $area * 2500 * 100
                );


        $monthFoodstuffChangeCost = ((int)$openShopSiteLocationModel->foodstuffMarginRate) > 0 ? bcmul($monthTurnoverEstimation,
            1 - bcdiv(((int)$openShopSiteLocationModel->foodstuffMarginRate), 100, 2)) : 0;


        $fixedCostMoney        = $fixedCost($openShopSiteLocationModel, $rentCost, $expenseAllocation);
        $monthProfitEstimation = (int)($monthTurnoverEstimation * (((int)$openShopSiteLocationModel->foodstuffMarginRate) / 100) - $fixedCostMoney);

        if ($monthProfitEstimation < 0) {
            $returnCircle = floor((($totalInvestmentEstimation
                    //- ((int)$openShopSiteLocationModel->deposit * 100)
                    - ($openShopSiteLocationModel->userContractRel ? ((int)$openShopSiteLocationModel->userContractRel->deposit) +
                        ((int)$openShopSiteLocationModel->userContractRel->decorationDeposit)
                        : 0)
                    - 30000 * 100) / $monthProfitEstimation));
        } elseif ($monthProfitEstimation > 0) {
            $returnCircle = ceil((($totalInvestmentEstimation
                    //- ((int)$openShopSiteLocationModel->deposit * 100)
                    - ($openShopSiteLocationModel->userContractRel ? ((int)$openShopSiteLocationModel->userContractRel->deposit) +
                        ((int)$openShopSiteLocationModel->userContractRel->decorationDeposit)
                        : 0)
                    - 30000 * 100) / $monthProfitEstimation));
        } else {
            $returnCircle = 0;
        }

        $dailyTurnover = (int)($fixedCostMoney / 30 / ((((int)$openShopSiteLocationModel->foodstuffMarginRate) ?: 65) / 100));

        return array_merge([
            "electricityFeeMonth" => $openShopSiteLocationModel->electricityFeeMonth,
            "waterFeeMonth"       => $openShopSiteLocationModel->waterFeeMonth,
            "rentCost"            => $rentCostShow,
            "expenseAllocation"   => $expenseAllocation
        ], [
            //食材毛利率
            "foodstuffMarginRate"      => $openShopSiteLocationModel->foodstuffMarginRate ?? 65,
            //月订单量
            "monthQuantityEstimation"  => ((int)$openShopSiteLocationModel->customerUnitPriceEstimation) > 0 ? bcdiv($monthTurnoverEstimation,
                ((int)$openShopSiteLocationModel->customerUnitPriceEstimation) * 100) : 0,
            //月营业额
            "monthTurnoverEstimation"  => $monthTurnoverEstimation,
            //月食材变动成本
            "monthFoodstuffChangeCost" => $monthFoodstuffChangeCost,
        ], [
            "monthProfitEstimation" => $monthProfitEstimation,
        ], [
            "dailyTurnover"             => (int)($fixedCostMoney / 30 / ((((int)$openShopSiteLocationModel->foodstuffMarginRate) ?: 65) / 100)),
            "dailySellAtCostOrderCount" => ceil((((int)$openShopSiteLocationModel->customerUnitPriceEstimation) > 0) ? ($dailyTurnover / ((int)$openShopSiteLocationModel->customerUnitPriceEstimation) / 100) : 0)
        ], [
            "totalInvestmentEstimation" => $totalInvestmentEstimation,
            "returnCycle"               => $returnCircle
        ]);
    }

    /**
     * @param $city
     * @param $power
     * @return int[]
     */
    public static function countFormStatusNumber($city, $power): array
    {
        $data = self::countHead($city, $power);
        Log::info('选址概览-' . json_encode($data, JSON_UNESCAPED_UNICODE));
        return $data;
    }

    /**
     * @param $city
     * @param $power
     * @return int[]
     */
    public static function countHead($city, $power): array
    {
        $statistics = function ($status) use ($city, $power) {
            return OpenShopSiteLocationModel::query()
                ->when(mb_strlen($city), function ($query) use ($city) {
                    $query->where('cityArea', 'like', "%$city%");
                })
                ->when(!$power['isAll'], function ($query) use ($power) {
                    $query->whereRaw($power['rawSql']);
                })
                ->whereIn('siteStatus', $status)
                ->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                ->count();
        };

        return [
            'toBeLocated'        => $statistics([OpenShopSiteLocationModel::SITE_STATUS_0, OpenShopSiteLocationModel::SITE_STATUS_1]),
            'submitted'          => 0,
            'pendingApproval'    => $statistics([OpenShopSiteLocationModel::SITE_STATUS_2, OpenShopSiteLocationModel::SITE_STATUS_10, OpenShopSiteLocationModel::SITE_STATUS_11]),
            'audited'            => 0,
            'completed'          => $statistics([OpenShopSiteLocationModel::SITE_STATUS_4]),
            'pendingUpdated'     => $statistics([OpenShopSiteLocationModel::SITE_STATUS_3]),
            'contractToBeUpload' => $statistics([OpenShopSiteLocationModel::SITE_STATUS_21])
        ];
    }

    /**
     * 获得选址概览
     * @param $list
     * @return int[]
     */
    public static function countNumber($list): array
    {
        $toBeLocated     = 0;
        $submitted       = 0;
        $pendingApproval = 0;
        $completed       = 0;
        $pendingUpdated  = 0;
        $audited         = 0;
        $contractToBeUpload  = 0;
        foreach ($list as $info) {
            if (!empty($info)) {
                if ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_0) {
                    if ($info['source'] == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP) {
                        $toBeLocated += 1;
                    }
                    if ($info['source'] == OpenShopSiteLocationModel::SOURCE_HOUSING) {
                        if ($info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_1 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_2 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_12 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_13) {
                            $toBeLocated += 1;
                        }
                        if ($info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_3) {
                            $pendingApproval += 1;
                        }
                        if ($info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_11) {
                            $audited += 1;
                        }
                        if ($info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_4) {
                            $pendingUpdated += 1;
                        }
                        if ($info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_0 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_5 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_6 || $info['clueStatus'] == OpenShopSiteLocationModel::CLUE_STATUS_10) {
                            $completed += 1;
                        }
                    }
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_1) {
                    $toBeLocated += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_2) {
                    $pendingApproval += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_10) {
                    $pendingApproval += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_3) {
                    $pendingUpdated += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_11) {
                    //概览归属于待审批
                    $pendingApproval += 1;
                    //$audited += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_4) {
                    $completed += 1;
                } elseif ($info['siteStatus'] == OpenShopSiteLocationModel::SITE_STATUS_21) {
                    $contractToBeUpload += 1;
                }
                //精确搜索
            }
        }
        return [
            'toBeLocated'     => $toBeLocated,
            'submitted'       => $submitted,
            'pendingApproval' => $pendingApproval,
            'audited'         => $audited,
            'completed'       => $completed,
            'pendingUpdated'  => $pendingUpdated,
            'contractToBeUpload' => $contractToBeUpload
        ];
    }

    public static function getSiteSurveyInfo($orderNo, $authInfo, $power)
    {
        $field = [
            'orderNo',
            'shopPattern',
            'patternType',
            'handler',
            'source',
            'mainProcessId',
            'id',
            'updatedAt',
            'siteStatus',
            'developConsultantName',
            'cityArea',
            'status',
            'provinceCode',
            'developConsultantId',
            'clueStatus',
            'bindId',
            'createdByUid',
            'updatedByUid',
            'messageFrom',
            'siteType',
            'shopModelType',
            'address',
            'mallName',
            'mallId',
            'isWhiteList',
            'mallGrade',
            'leaseFiles',
            'signatureTime',
            'ctFixedRent',
            'ctRentType',
            'ctRentPaymentCycle',
            'ctDeposit',
            'ctOtherFee',
            'ctRemind',
            'ctPropertyFee',
            'ctMobilizationFee',
            'ctTransferFee',
            'ctBond',
            'ctManageFee',
            'ctSponsorshipFee',
            'ctPromotionFee',
            'siteSelection',
            'sellingCategory',
        ];
        $info  = OpenShopSiteLocationModel::query()
                                          ->select($field)
                                          ->with('locationRel')
                                          ->with('signOrderRel')
                                          ->with('baseUserInfoRel')
                                          ->whereIn('source',
                                              [
                                                  OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                  OpenShopSiteLocationModel::SOURCE_HOUSING
                                              ])
                                          ->with([
                                              'examineLogsRel' => function ($query) {
                                                  $query->where('status',
                                                      OpenShopSiteLocationExamineLogModel::STATUS_OK);
                                              }
                                          ])
                                          ->with('baseUserContractRel')
                                          ->with([
                                              'orderManagerRel' => function ($query) {
                                                  $query->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_1);
                                              }
                                          ])
                                          ->where('orderNo', $orderNo)
                                          ->first();

        if (empty($info)) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NOT_EXIST);
        }
        //获取省区负责人
        $provinceInfoBy = OrganizationManageService::getProvinceInfoByProvinceCode($info->provinceCode ?: ($info['baseUserInfoRel']['chooseShopProvinceCode'] ?? 0));

        $idInfo        = OpenShopUserIdentityCardModel::query()
                                                      ->where('orderNo', $info['orderNo'])
                                                      ->first();
        //获取店铺code
        $shopCode = OpenShopSignOrderModel::query()->where('orderNo', $info['orderNo'])->value('shopCode');
//        //获取rms用户信息
//        if (isset($info['baseUserContractRel'])) {
//            $rmsUser = RmsUserService::getRmsUserInfoByUserIds([$info['baseUserContractRel']['createdByUid']]);
//        }
        if (isset($provinceInfoBy['developUid']) && ($provinceInfoBy['developUid'] == $authInfo['userId'])) {
            $siteStatusText = OpenShopSiteLocationModel::CN_PROVINCE_STATUS[$info['siteStatus']];
        } else {
            $siteStatusText = OpenShopSiteLocationModel::CN_STATUS[$info['siteStatus']];
        }
        //查询审批意见  省总审批意见
        $content = OpenShopSiteLocationExamineLogModel::query()
                                                      ->where('orderNo', $info['orderNo'])
                                                      ->where('position',
                                                          OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE)
                                                      ->orderBy('id', 'DESC')
                                                      ->value('content');

        try {
            $updatedBy = collect(RmsUserRemote::getRmsUserByIds([$info->updatedByUid ?? $info->createdByUid],
                ['id', 'username']))->first();
        } catch (\Exception $exception) {
            $updatedBy = '山治(石尧)';
        }

        $selectionSurvey = [
            'id'                    => $info['id'],
            'updatedAt'             => $info['updatedAt']->toDateTimeString(),
            'siteStatus'            => $info['siteStatus'],
            'siteStatusText'        => $siteStatusText,
            'approvalOpinions'      => $content ?? '-',
            'developmentConsultant' => $info['developConsultantName'] ?? '暂无',
            'provincialHead'        => $provinceInfoBy['operationName'] ?? '暂无',
            'isToStore'             => OpenShopSiteLocationExamineLogModel::IS_TO_STORE_MAPPING[($info['examineLogsRel'][0]['isToStore'] ?? 0)] ?? '-',
            'updatedBy'             => $updatedBy['username'] ?? ''
        ];
        $mobile          = [];
        if (isset($info['baseUserInfoRel'])) {
            if ($info['baseUserInfoRel']['mobile']) {
                $mobile[] = $info['baseUserInfoRel']['mobile'];
            }
            if ($info['baseUserInfoRel']['remarkMobile1']) {
                $mobile[] = $info['baseUserInfoRel']['remarkMobile1'];
            }
            if ($info['baseUserInfoRel']['remarkMobile2']) {
                $mobile[] = $info['baseUserInfoRel']['remarkMobile2'];
            }
        }
        $franchiseeInformation = [
            'name'         => $idInfo['name'] ?? '-',
            'age'          => (string)optional($idInfo)->birthday ? (date('Y') - (int)substr($idInfo['birthday'], 0, 4)) : 0,
            'siteLocation' => $info['baseUserInfoRel']['chooseShopAddressPrefix'] ?? '-',
            'provinceCode' => $info['baseUserInfoRel']['chooseShopProvinceCode'] ?? 0,
            'mobile'       => $mobile,
            'email'        => $info['baseUserInfoRel']['email'] ?? '-',
            'branch'       => $provinceInfoBy['name'] ?? '-'
        ];
        $investmentInformation = [
            'investmentConsultant'  => $info['orderManagerRel'][0]['managerName'] ?? '无',
            'shopCode'              => $shopCode,
            'createdAt'             => !empty($info['signOrderRel']) ? ($info['signOrderRel']['signTime'] ? date('Y-m-d H:i:s',
                $info['signOrderRel']['signTime']) : '-') : '-',
            'initialFee'            => $info['baseUserContractRel']['initialFee'] ?? 0,
            'technologyTransferFee' => $info['baseUserContractRel']['technologyTransferFee'] ?? 0,
            'deposit'               => $info['baseUserContractRel']['deposit'] ?? 0,
            'managementCost'        => $info['baseUserContractRel']['managementCost'] ?? 0,
            'decorationDeposit'     => $info['baseUserContractRel']['decorationDeposit'] ?? 0,
            'remark'                => $info['baseUserContractRel']['remark'] ?? '-',
            'operateSubsidyAmount'  => $info['baseUserContractRel']['operateSubsidyAmount'] ?? 0,
            'kindSubsidyAmount'     => $info['baseUserContractRel']['kindSubsidyAmount'] ?? 0,
        ];
        //按钮后台控制  按钮逻辑
        $siteManager           = ConfigModel::getManager(ConfigModel::SITE_MANAGER);
        $siteSuperManager      = ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
        $sitePlaceholderManage = ConfigModel::getManager(ConfigModel::SITE_PLACEHOLDER_ADMIN);
//        $approverName          = (function (int $siteStatus) use (
//            $info,
//            $provinceInfoBy,
//            $siteSuperManager,
//            $siteManager
//        ) {
//            switch ($siteStatus) {
//                case OpenShopSiteLocationModel::SITE_STATUS_2:
//                    //判断还没有审批的那一个人
//                    //获得已审批的人的UserId
//                    $approveUserIds = OpenShopSiteLocationExamineLogModel::getExaminersOk($info->orderNo);
//                    if ($approveUserIds) {
//                        //简单一点判断是否为省总去决定显示谁
//                        in_array($provinceInfoBy['operationUid'], $approveUserIds) ? ($approverName = implode(',',
//                            array_column(RmsUserRemote::getRmsUserByIds($siteManager),
//                                'username'))) : ($approverName = $provinceInfoBy['operationName']);
//
//                        if (count($approveUserIds) >= 2) {
//                            $verify = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL);
//                            $approverName = implode(',', array_column(RmsUserRemote::getRmsUserByIds($verify), 'username'));
//                        }
//
//                    } else {
//                        $approverName = implode(',', array_column(RmsUserRemote::getRmsUserByIds($siteManager),
//                                'username')) . ',' . $provinceInfoBy['operationName'];
//                    }
//                    break;
//                case OpenShopSiteLocationModel::SITE_STATUS_10:
//                    $approverName = implode(',',
//                        array_column(RmsUserRemote::getRmsUserByIds($siteManager), 'username'));
//                    break;
//                case OpenShopSiteLocationModel::SITE_STATUS_11:
//                    $approverName = implode(',',
//                        array_column(RmsUserRemote::getRmsUserByIds($siteSuperManager), 'username'));
//                    break;
//                default:
//                    $approverName = '-';
//            }
//            return $approverName;
//        })($info->siteStatus);
        $approverName = '-';
        //获取处理人
        if (mb_strlen($info->handler)) {
            $approverNameArr = RmsUserRemote::getRmsUserByIds(explode(',', $info->handler), ['username']);
            $approverName    = implode(',', collect($approverNameArr)->pluck('username')->toArray());
        }
        $isShowSiteButton   = false;
        $siteButtonText     = '查看选址评估';
        $isShowAssignButton = false;
        $isShowHouseButton  = false;

        //省区开发  看省区的按钮
        $manageUser = OpenShopOrganizationManageUserModel::query()
                                                         ->where('userId', $authInfo['userId'])
                                                         ->where('type', OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP)
                                                         ->with(['manageRel.regionRel'])
                                                         ->get();
        if ($manageUser->count()) {
            $provinces = [];
            $manageUser->map(function ($manageUser) use (&$provinces){
                try {
                    $addProvinceCodes = $manageUser->manageRel->regionRel->pluck('provinceCode')->toArray();
                } catch (\Exception $exception) {
                    $addProvinceCodes = [];
                }
                $provinces = array_merge($provinces, $addProvinceCodes);
            });

            $orderNos  = OpenShopSiteLocationModel::query()
                                                  ->where(function ($query) use ($authInfo, $provinces) {
                                                      $query->whereIn('provinceCode', $provinces)
                                                            ->orWhere('createdByUid', $authInfo['userId'])
                                                            ->orWhere('developConsultantId', $authInfo['userId']);
                                                  })
                                                  ->pluck('orderNo')->toArray();
        }

        //开发
        if ($authInfo['userId'] == $info->developConsultantId) {
            //对自己展示查看
            $isShowSiteButton = true;
            //对自己展示填写   填写选址报告  状态默认为0  兼容不了 拆开来写
            if (in_array($info->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_2,
                    OpenShopSiteLocationModel::CLUE_STATUS_4
                ]) || in_array($info->siteStatus,
                    [OpenShopSiteLocationModel::SITE_STATUS_0, OpenShopSiteLocationModel::SITE_STATUS_3])) {
                $siteButtonText = '填写选址评估';
            }
            if ($info->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && in_array($info->siteStatus, [
                    OpenShopSiteLocationModel::SITE_STATUS_0,
                    OpenShopSiteLocationModel::SITE_STATUS_1,
                    OpenShopSiteLocationModel::SITE_STATUS_3
                ])) {
                $siteButtonText    = '填写选址评估';
                $isShowHouseButton = true;
            }
            if ($info->source == OpenShopSiteLocationModel::SOURCE_HOUSING && in_array($info->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_0,
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13
                ])) {
                $isShowSiteButton = false;
            }
        }

        if (($authInfo['userId'] == $provinceInfoBy['developUid'] || in_array($authInfo['userId'],
                    $siteManager)) && $info->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_1) {
            $isShowAssignButton = true;
        }

        //主要处理 [isAll == true] 时的查看选址报告
        if ($power['isAll'] || $authInfo['userId'] == $provinceInfoBy['developUid'] || in_array($info->orderNo,
                ($orderNos ?? []))) {
            if (in_array($info->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_3,
                    OpenShopSiteLocationModel::CLUE_STATUS_11,
                    OpenShopSiteLocationModel::CLUE_STATUS_5,
                    //OpenShopSiteLocationModel::CLUE_STATUS_10,
                    OpenShopSiteLocationModel::CLUE_STATUS_6,
                ]) || in_array($info->siteStatus, [
                    OpenShopSiteLocationModel::SITE_STATUS_3,
                    OpenShopSiteLocationModel::SITE_STATUS_2,
                    OpenShopSiteLocationModel::SITE_STATUS_4,
                    OpenShopSiteLocationModel::SITE_STATUS_11,
                    OpenShopSiteLocationModel::SITE_STATUS_10,
                ])) {
                $isShowSiteButton = true;
            }
        }
        //判断是否为复盘  展示立即复盘
        if ($info->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && $info->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4) {
            //复盘人
            $replayUserIds = [];
            OpenShopSiteLocationReplayModel::query()
                                           ->where('orderNo', $info->orderNo)
                                           ->get()
                                           ->each(function ($item) use (&$replayUserIds) {
                                               if (!mb_strlen($item->content)) {
                                                   $replayUserIds[] = $item->createdByUid;
                                               }
                                           });
            if (in_array($authInfo['userId'], $replayUserIds)) {
                $siteButtonText     = '立即复盘';
                $isShowAssignButton = true;
            }
        }

        if ($info->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && $info->bindId == OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE && $info->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_0) {
            $isShowSiteButton = false;
        }

        //$authInfo['userId']
        $businessConfirmSiteLocation = OpenShopSiteLocationExamineLogModel::query()
                                                                          ->where("orderNo", $info->orderNo)
                                                                          ->where("type",
                                                                              OpenShopSiteLocationExamineLogModel::TYPE_BUSINESS_CONFIRM_SITE_LOCATION)
                                                                          ->where("updatedAt", 0)
                                                                          ->orderBy("id", "desc")
                                                                          ->first();
        // 获取预占点位信息
        $placeholder = new PlaceHolderSiteLocationService($info['orderNo']);

        $placeholderInfo         = $placeholder->getPlaceholderInfo();
        $placeholderInfoResource = empty($placeholderInfo) ? null :
            PlaceHolderSiteLocationResource::collection([$placeholderInfo])->getIterator()->current();

        // 展示预占位信息
        $isShowPlaceholderAudit = false;
        if (!empty($placeholderInfo) && $info->signOrderRel->isPlaceholder) {
            // 判断 状态
            switch ($placeholderInfo->siteStatus) {
                // 省总审批
                case OpenShopSiteLocationModel::SITE_STATUS_10:
                    if (in_array($authInfo['userId'], [$provinceInfoBy['operationUid']])) {
                        $isShowPlaceholderAudit = true;
                    }
                    break;
                case OpenShopSiteLocationModel::SITE_STATUS_11:
                    if (in_array($authInfo['userId'], $sitePlaceholderManage)) {
                        $isShowPlaceholderAudit = true;
                    }
                    break;
            }
        }

        // 获取房源信息
        $fyInfo = null;
        if ($info->bindId > 0) {
            $fyInfo = [
                'title'           => '房源信息（FY' . $info->id . '）',
                'fyCode'          => 'FY' . $info->id,
                'id'              => $info->id,
                'messageFrom'     => $info->messageFrom,
                'messageFromText' => SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$info->messageFrom] ?? '',
                'shopModelType'   => SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$info->shopModelType] ?? '',
                'shopPattern'     => $info->shopPattern,
                'shopPatternStr'  => OpenShopSiteLocationModel::SHOP_PATTERN_MAPPING[$info->shopPattern] ?? '-',
                'patternType'     => $info->patternType,
                'patternTypeStr'  => OpenShopSiteLocationModel::getPatternTypeStr($info->patternType),
                'address'         => $info->address,
                'recommendFloor'  => strlen($info->mallId) ? (SiteLocationMallModel::getRecommendFloorInfo((string)$info->mallId)['recommendFloor'] ?: '') : '',
                'mallName'        => $info->mallName,
                'isWhiteList'     => (bool)$info->isWhiteList,
                'mallGrade'       => $info->mallGrade,
                'mallStatus'      => $info->mallStatus,
                'mallStatusText'  => SiteLocationEnum::MALL_STATUS_TEXT[$info->mallStatus] ?? '',
                'siteSelection'   => $info->siteSelection,
                'sellingCategory' => $info->sellingCategory,
            ];
        }

        //先判断是否展示租赁信息
        $isShowLeaseContract = false;
        if (($info->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 && $info->signatureTime) || in_array($info->siteStatus, [OpenShopSiteLocationModel::SITE_STATUS_21, OpenShopSiteLocationModel::SITE_STATUS_22])) {
            $isShowLeaseContract = true;
        }

        switch ($info->ctRentType) {
//            case SiteLocationEnum::RENT_TYPE_1:
//                $dwt = $info->ctFixedRent ? ('(' . $info->ctFixedRent .  '元)') : '';
//                break;
            case SiteLocationEnum::RENT_TYPE_2:
                $dwt = $info->ctRemind ? ('(' . $info->ctRemind .  '%)') : '';
                break;
            case SiteLocationEnum::RENT_TYPE_3:
            case SiteLocationEnum::RENT_TYPE_4:
                $dwt = $info->ctFixedRent ? ('(' . $info->ctRemind . '%)') : '';
                break;
            default:
                $dwt = '';
        }

        $leaseInfo = [
            'signatureTime' => $info->signatureTime ? formatDateYmd($info->signatureTime) : '未填写',
            'ctFixedRent'   => $info->signatureTime ? $info->ctFixedRent : '未填写',
            'ctRentType'    => $info->signatureTime ? ((SiteLocationEnum::RENT_PAYMENT_TEXT[$info->ctRentPaymentCycle] ?? '') . '+' . (SiteLocationEnum::RENT_TYPE_TEXT[$info->ctRentType] ?? '') . $dwt) : '未填写',
            'ctDeposit'     => $info->signatureTime ? $info->ctDeposit : '未填写',
            'ctOtherFee'    => $info->signatureTime ? ((float)$info->ctPropertyFee + (float)$info->ctMobilizationFee + (float)$info->ctTransferFee + (float)$info->ctBond + (float)$info->ctManageFee + (float)$info->ctSponsorshipFee + (float)$info->ctPromotionFee + (float)$info->ctOtherFee) : '未填写',
        ];

        //判断租赁合同的按钮文案
        $leaseContractButtonText   = '查看租赁合同信息';
        $isShowLeaseContractButton = false;
        if ($info->developConsultantId == $authInfo['userId'] && $info->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_21) {
            $leaseContractButtonText   = '填写租赁合同信息';
            $isShowLeaseContractButton = true;
        }

        if (in_array($info->siteStatus, [OpenShopSiteLocationModel::SITE_STATUS_4, OpenShopSiteLocationModel::SITE_STATUS_22])) {
            $isShowLeaseContractButton = true;
        }

        return [
            'selectionSurvey'              => $selectionSurvey,
            'replay'                       => self::getReplayByOrderNo($info->orderNo, $authInfo['userId']),
            'franchiseeInformation'        => $franchiseeInformation,
            'investmentInformation'        => $investmentInformation,
            'signOrderCostLists'           => optional($info->baseUserContractRel)->signOrderCostLists() ?: [],
            "approval"                     => self::getApprovalRecord($info->orderNo),
            'placeholderInfo'              => $placeholderInfoResource,
            "approverName"                 => $approverName,
            'fyInfo'                       => $fyInfo,
            'isShowLeaseContract'          => $isShowLeaseContract, //控制div是否显示
            'leaseInfo'                    => $leaseInfo,           //租赁合同详情
            "siteButtonText"               => $siteButtonText,       // 按钮文字描述
            "isShowSiteButton"             => $isShowSiteButton,     // 是否显示按钮
            "isShowAssignButton"           => $isShowAssignButton,   // 是否显示待分配
            "isShowHouseButton"            => $isShowHouseButton,    // 是否显示房源线索
            'isShowPlaceholderAuditButton' => $isShowPlaceholderAudit, // 是否显示预占址审核按钮
            "businessRejectStatus"         => $businessConfirmSiteLocation && $businessConfirmSiteLocation->status == OpenShopSiteLocationExamineLogModel::STATUS_REFUSE,
            "isShowLeaseContractButton"    => $isShowLeaseContractButton,   //是否展示租赁合同按钮
            "leaseContractButtonText"      => $leaseContractButtonText,  //租赁合同按钮文案
            "id"                           => $info->id,   //id
        ];
    }

    /**
     * 后台新增选址相关信息
     * @param string $orderNo
     * @return array
     */
    public static function adminSiteLocation(string $orderNo): array
    {
        // 1.工程条件
        $siteLocation = OpenShopSiteLocationModel::query()->where('orderNo', $orderNo)->whereIn('source',
            [
                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                OpenShopSiteLocationModel::SOURCE_HOUSING
            ])->first();
        if ($siteLocation) {
            $engineerCondition = [
                'decorationShopTypeText'      => SiteLocationEnum::DECORATION_SHOP_TEXT[$siteLocation->decorationShopType] ?? '',
                'doorWidth'                   => $siteLocation->doorWidth,
                'shopWidth'                   => $siteLocation->shopWidth,
                'floorHeight'                 => $siteLocation->floorHeight,
                'depth'                       => $siteLocation->depth,
                'area'                        => $siteLocation->area,
                'electricityConsumption'      => $siteLocation->electricityConsumption,
                'isCapacityIncreaseText'      => SiteLocationEnum::IS_CAPACITY_INCREASE_TEXT[$siteLocation->isCapacityIncrease] ?? '',
                'capacityIncreaseFee'         => $siteLocation->capacityIncreaseFee,
                'exhaustAirVolume'            => $siteLocation->exhaustAirVolume,
                'isExhaustReconstructionText' => SiteLocationEnum::IS_EXHAUST_RECONSTRUCTION_TEXT[$siteLocation->isExhaustReconstruction] ?? '',
                'upperWaterDiameter'          => $siteLocation->upperWaterDiameter,
                'lowerWaterDiameter'          => $siteLocation->lowerWaterDiameter,
                'isReformWaterText'           => SiteLocationEnum::IS_REFORM_WATER_TEXT[$siteLocation->isReformWater] ?? '',
                'airConditionerCTypeText'     => SiteLocationEnum::AIR_CONDITIONER_TYPE_TEXT[$siteLocation->airConditionerCType] ?? '',
                'isFireControl'               => SiteLocationEnum::IS_FIRE_CONTROL_TEXT[$siteLocation->isFireControl] ?? '',
                'adSpaceNumber'               => $siteLocation->adSpaceNumber,
            ];
        } else {
            $engineerCondition = (object)[];
        }

        // 2.门店照片
        $sitePics = OpenShopUploadFileResourceModel::query()
                                                   ->where('orderNo', $orderNo)
                                                   ->whereIn('position',
                                                       array_keys(UploadFileResourceEnum::SITE_LOCATION_PHOTO_LIST))
                                                   ->get()
                                                   ->map(function ($item) {
                                                       return [
                                                           'path'          => $item->formatUrl,
                                                           'positionField' => UploadFileResourceEnum::SITE_LOCATION_PHOTO_LIST[$item['position']] ?? '',
                                                           'positionText'  => UploadFileResourceEnum::SITE_LOCATION_PHOTO_TEXT[$item['position']] ?? '',
                                                       ];
                                                   })
                                                   ->toArray();

        return [
            'engineerCondition' => $engineerCondition,
            'sitePics'          => $sitePics,
        ];
    }

    public static function getSiteSurveyList(
        $number,
        $name,
        $shopCode,
        $source,
        $status,
        $filterType,
        $filterValue,
        $pageNum,
        $pageSize,
        $power,
        $handle,
        $userId,
        string $developConsultantIds = ""
    ) {
        //判断个人权限或者省区总  -- 管理员所有权限默认不做处理
//        $developConsultantId = 0;
//        $areaArr             = [];
//        if ($scope != PermissionService::PERMISSION_ALL) {
//            if ($scope == PermissionService::PERMISSION_DENY) {
//                return [];
//            }
//            if ($position == SiteLocationEnum::POSITION_PROVINCE_CHIEF || $scope == PermissionService::PERMISSION_PROVINCE) {
//                $areaArr = OrganizationManageService::getProvinceList($userId);
//            } else {
//                $developConsultantId = $userId;
//            }
//        }

        $orderNosTemp  = [];
        $orderNosTemp1 = [];
        //根据姓名模糊匹配单号
        if (mb_strlen($name)) {
            OpenShopUserIdentityCardModel::query()
                                         ->with(['mainProcessRel'])
                                         ->where('name', 'like', "%$name%")
                                         ->get()
                                         ->each(function ($item) use (&$orderNosTemp) {
                                             if ($item->mainProcessRel != null) {
                                                 foreach ($item->mainProcessRel as $value) {
                                                     $orderNosTemp[] = $value->orderNo;
                                                 }
                                             }
                                         });
        }
        if (mb_strlen($shopCode)) {
            $orderNosTemp1 = OpenShopSignOrderModel::query()
                                                   ->where('shopCode', 'like', "%$shopCode%")
                                                   ->pluck('orderNo');
        }
        $paginator = OpenShopSiteLocationModel::query()
                                              ->where('createdByUid', '<>', 14)
                                              ->whereIn('source',
                                                  [
                                                      OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                      OpenShopSiteLocationModel::SOURCE_HOUSING
                                                  ])
                                              ->when(strlen($developConsultantIds) > 0,
                                                  function ($query) use ($developConsultantIds) {
                                                      $query->whereIn('developConsultantId',
                                                          explode(",", $developConsultantIds));
                                                  })
                                              ->when($handle, function ($query) use ($userId) {
                                                      $query->whereRaw("FIND_IN_SET({$userId}, `handler`) != 0");
                                                  })
                                              ->when(mb_strlen($filterType),
                                                  function ($query) use ($filterType, $filterValue) {
                                                      if ($filterType == OpenShopOrganizationManageModel::TYPE_COMPANY) {
                                                          //获得分公司所对应的所有省区code
                                                          if ($filterValue != OpenShopOrganizationManageModel::HEADQUARTERS_ID) {
                                                              $provinceCode = OpenShopOrganizationRegionMappingModel::query()
                                                                                                                    ->where('manageId',
                                                                                                                        $filterValue)
                                                                                                                    ->pluck('provinceCode')
                                                                                                                    ->toArray();
                                                              $query->whereIn('provinceCode', $provinceCode);
                                                          }
                                                      }
                                                      if ($filterType == OpenShopOrganizationManageModel::TYPE_PROVINCE) {
                                                          //根据省区code去搜索
                                                          $query->where('provinceCode', $filterValue);
                                                      }
                                                      if ($filterType == OpenShopOrganizationManageModel::TYPE_CITY) {
                                                          //根据市区code去搜索
                                                          $query->where('cityCode', $filterValue);
                                                      }
                                                  })
//                                              ->when(mb_strlen($number), function ($query) use ($number) {
//                                                  $query->where('orderNo', "like", '%' . strtoupper($number) . '%');
//                                              })
                                              ->when(mb_strlen($source), function ($query) use ($source) {
                $source = explode(',', $source);
                $query->whereIn('source', $source);
            })
                                              ->where(function ($query) use ($status) {
                                                  $query->when(mb_strlen($status), function ($query) use ($status) {
                                                      $status = explode(',', $status);
                                                      foreach ($status as $value) {
                                                          if ($value == OpenShopSiteLocationModel::SITE_STATUS_0) {
                                                              $query->orWhere('siteStatus',
                                                                  OpenShopSiteLocationModel::SITE_STATUS_1)
                                                                    ->orWhere(function ($query) {
                                                                        $query->where('source',
                                                                            OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                                                                              ->where('siteStatus',
                                                                                  OpenShopSiteLocationModel::SITE_STATUS_0);
                                                                    })
                                                                    ->orWhereIn('clueStatus', [
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_1,
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_2,
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_12,
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_13,
                                                                    ]);
                                                          } elseif ($value == OpenShopSiteLocationModel::SITE_STATUS_2) {
                                                              $query->orWhereIn('siteStatus',
                                                                  [
                                                                      OpenShopSiteLocationModel::SITE_STATUS_2,
                                                                      OpenShopSiteLocationModel::SITE_STATUS_10
                                                                  ])
                                                                    ->orWhere('clueStatus',
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_3);
                                                          } elseif ($value == OpenShopSiteLocationModel::SITE_STATUS_3) {
                                                              $query->orWhere('siteStatus', $value)
                                                                    ->orWhere('clueStatus',
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_4);
                                                          } elseif ($value == OpenShopSiteLocationModel::SITE_STATUS_4) {
                                                              $query->orWhere('siteStatus', $value)
                                                                    ->orWhere(function ($query) {
                                                                        $query->where('source',
                                                                            OpenShopSiteLocationModel::SOURCE_HOUSING)
                                                                              ->whereIn('clueStatus', [
                                                                                  OpenShopSiteLocationModel::CLUE_STATUS_0,
                                                                                  OpenShopSiteLocationModel::CLUE_STATUS_6,
                                                                                  OpenShopSiteLocationModel::CLUE_STATUS_10,
                                                                              ]);
                                                                    })
                                                                    ->orWhere('clueStatus',
                                                                        OpenShopSiteLocationModel::CLUE_STATUS_5);
                                                          } elseif ($value == OpenShopSiteLocationModel::SITE_STATUS_11) {
                                                              $query->orWhere('siteStatus', $value)
                                                                    ->orWhere('clueStatus', $value);
                                                          } else {
                                                              $query->orWhere('siteStatus', $value);
                                                          }
                                                      }
                                                  });
                                              })
                                              ->when(mb_strlen($name), function ($query) use ($orderNosTemp) {
                                                  $query->whereIn('orderNo', $orderNosTemp);
                                              })
                                              ->when(mb_strlen($shopCode) || mb_strlen($number),
                                                  function ($query) use ($shopCode, $orderNosTemp1, $number) {
                                                      if (mb_strlen($shopCode) && mb_strlen($number) && str_contains(strtoupper($number), "FY")) {
                                                          $query->whereIn('orderNo', $orderNosTemp1)
                                                                ->orWhere('orderNo', "like",
                                                                    '%' . strtoupper($number) . '%');
                                                      } else {
                                                          if (mb_strlen($shopCode)) {
                                                              $query->whereIn('orderNo', $orderNosTemp1);
                                                          }
                                                          if (mb_strlen($number) && !str_contains(strtoupper($number), "FY")) {
                                                              $query->orWhere('id', $number);
                                                          }

                                                          if (mb_strlen($number) && str_contains(strtoupper($number), "FY")) {
                                                              $query->where('orderNo', "like",
                                                                  '%' . strtoupper($number) . '%');
                                                          }
                                                      }

                                                  })
//          ->when($userId == config('duty.siteLocationDutyId'),
//              function ($query) use ($userId) {
//                  $query->orWhere('siteStatus',
//                      OpenShopSiteLocationModel::SITE_STATUS_11)
//                        ->orWhere('clueStatus',
//                            OpenShopSiteLocationModel::CLUE_STATUS_11);
//              })
                                              ->when(!$power['isAll'], function ($query) use ($power) {
                $query->whereRaw($power['rawSql']);
            })
                                              ->orderByDesc('updatedAt')
                                              ->with([
                                                  'signOrderRel',
                                                  'identityCardRel',
                                                  'baseUserInfoRel',
                                                  'mainProcessRel',
                                                  'relationWangguiRel',
                                              ])
                                              ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        //获取创建人
        $userList = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());

        $rmsUserIds = $userList['data'] ?: [];

        //获得每个人的入职时间
        $joinTime = KmsUser::query()
            ->whereIn('rmsUserId', array_column($rmsUserIds, 'id'))
            ->pluck('joinTime', 'rmsUserId')
            ->toArray();

        //提交日志
        $submitModel = OpenShopSiteLocationExamineLogModel::query()
            ->whereIn('createdByUid', array_column($rmsUserIds, 'id'))
            ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_SITE_FROM_SUBMIT)
            ->withoutGlobalScope('isDel');
        //获得首次提交的订单
        $submitOrderNo = $submitModel->groupBy('createdByUid')
            ->pluck('orderNo')
            ->toArray();

        //获得首次提交的人
        $submitTempCount = [];
        $submitModel->each(function (OpenShopSiteLocationExamineLogModel $openShopSiteLocationExamineLogModel) use (&$submitTempCount) {
            $submitTempCount[] = $openShopSiteLocationExamineLogModel->createdByUid;
        });
        $submitOnlyOneCount = [];
        $tempSubmit = array_count_values($submitTempCount);
        foreach ($tempSubmit as $userId => $count) {
            if ($count == 1) {
                $submitOnlyOneCount[] = $userId;
            }
        }

        $list     = $paginator->map(function ($item) use ($userList, $joinTime, $submitOrderNo, $submitOnlyOneCount) {
            //判断任务类型
            if ($item->source == OpenShopSiteLocationModel::SOURCE_HOUSING && $item->bindId == OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE) {
                $info = '';
                foreach (($userList['data'] ?? []) as $user) {
                    if ($user['id'] == $item->createdByUid) {
                        $info = $user['username'];
                    }
                }
                $siteOrClue = 1;
                $cityArea   = $item->cityArea;
                $statusText = OpenShopSiteLocationModel::SITE_LOCATION_CLUE_MAPPING[$item->clueStatus];
                $status     = $item->clueStatus;
                $number     = $item->orderNo; //编号
            } else {
                $siteOrClue = 0;
                $info       = (optional($item->identityCardRel)->name ?: '-') . ' ' . (optional($item->signOrderRel)->shopCode ?: '-');
                //$cityArea   = optional($item->baseUserInfoRel)->chooseShopAddressPrefix ?: '-';  选址1.1.2优化  取消意向选址范围
                $cityArea   = $item->bindId ? $item->cityArea : (string)optional($item->baseUserInfoRel)->chooseShopAddressPrefix;
                $statusText = OpenShopSiteLocationModel::CN_PROVINCE_STATUS[$item->siteStatus] ?? '-';
                $status     = $item->siteStatus;
                $number     = optional($item->signOrderRel)->shopCode ?: '-'; //编号
            }
            $tag = '';

            if (in_array($item->siteStatus, [
                OpenShopSiteLocationModel::SITE_STATUS_2,
                OpenShopSiteLocationModel::SITE_STATUS_3,
                OpenShopSiteLocationModel::SITE_STATUS_4,
                OpenShopSiteLocationModel::SITE_STATUS_10,
                OpenShopSiteLocationModel::SITE_STATUS_11,
                OpenShopSiteLocationModel::SITE_STATUS_20,
                OpenShopSiteLocationModel::SITE_STATUS_21,
            ]) || in_array($item->clueStatus, [
                OpenShopSiteLocationModel::CLUE_STATUS_3,
                OpenShopSiteLocationModel::CLUE_STATUS_4,
                OpenShopSiteLocationModel::CLUE_STATUS_5,
                OpenShopSiteLocationModel::CLUE_STATUS_6,
                OpenShopSiteLocationModel::CLUE_STATUS_10,
                OpenShopSiteLocationModel::CLUE_STATUS_11,
                OpenShopSiteLocationModel::CLUE_STATUS_13,
                ])) {
                if (time() < (($joinTime[$item->developConsultantId] ?? 0) + 86400 * 60)) {
                    $tag = '新人提交';
                }

                if (in_array($item->orderNo, $submitOrderNo) && in_array($item->developConsultantId, $submitOnlyOneCount)) {
                    $tag = '首次提交';
                }
            }

            // 底部tag
            $bottomTags = [];
            // 门型
            if ($item->shopType) {
                $shopTypeArr = Cache::remember('site_location_shop_type', 3600, function () {
                    return collect(RmsShopRemote::getShopAttributeData())->where('name', '店型')->first()['value'] ?? [];
                });
                $text = collect($shopTypeArr)->where('id', $item->shopType)->first()['name'] ?? '';

                if ($text != '') {
                    $bottomTags[] = [
                        'text'  => $text,
                        'color' => 'grey',
                    ];
                }
            }
            // 关联网规
            if ($item->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
                if (!in_array($item->mallGrade, ['', '未评级'])) {
                    $bottomTags[] = [
                        'text'  => str_replace('级', '', $item->mallGrade) . '商',
                        'color' => 'grey',
                    ];
                } else {
                    $bottomTags[] = [
                        'text'  => '商场',
                        'color' => 'grey',
                    ];
                }
            }


            if (in_array($item->shopModelType, [SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_SCHOOL])) {
                if (
                    $item->relationWangguiRel != null
                    && $item->relationWangguiRel->match == OpenShopSiteLocationWangguiRelationModel::MATCH_ON
                    && isset(ProgrammingEnum::PC_GRADE_MAPPING[$item->relationWangguiRel->grade])
                ) {
                    if ($item->relationWangguiRel->type == OpenShopSiteLocationWangguiRelationModel::TYPE_COMMUNITY) {
                        $tempTag = [
                            'text'  => ProgrammingEnum::PC_GRADE_MAPPING[$item->relationWangguiRel->grade] . '区',
                            'color' => 'grey',
                        ];
                    } else {
                        $tempTag = [
                            'text'  => ProgrammingEnum::PC_GRADE_MAPPING[$item->relationWangguiRel->grade] . '街',
                            'color' => 'grey',
                        ];
                    }
                    $bottomTags[] = $tempTag;
                } else {
                    $bottomTags[] = [
                        'text'  => '街道',
                        'color' => 'grey',
                    ];
                }
            }

            // 销售品类
            if ($item->shopPattern && $item->patternType) {
                $bottomTags[] = [
                    'text'  => OpenShopSiteLocationModel::getPatternTypeStr($item->patternType),
                    'color' => 'grey',
                ];
            }



            return [
                'id'                    => $item->id,
                'orderNo'               => $item->orderNo,
                'statusText'            => $statusText,
                'status'                => $status,
                'cityArea'              => $cityArea,
                'info'                  => $info,
                'tag'                   => $tag,
                'updatedAt'             => date('Y-m-d H:i:s', $item->updatedAt->timestamp),
                'siteOrClue'            => $siteOrClue,
                'number'                => $number,
                'developConsultantName' => $item->developConsultantName ?: '待指派开发顾问',
                'messageFrom'           => $item->messageFrom,
                "messageFromText"       => (function ($messageFrom) {
                    $messageFromText = "";
                    switch ($messageFrom) {
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_1:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_3:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_7:
                            $messageFromText = "自带址";
                            break;
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_2:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_6:
                            $messageFromText = "推荐址";
                            break;
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_5:
                            $messageFromText = "转让";
                            break;
                    }
                    return $messageFromText;
                })($item->messageFrom),
                'tags'           => collect(OrderService::getOrderTags(
                    1,
                    self::tagLocationStatus($item),
                ))->where('name', '迁')->values(),
                'bottomTags' => $bottomTags,
            ];
        });

        $isShowDetail = true;
        if ($power['role'] == \App\Service\OpenShop\SiteLocation\PermissionService::ROLE_ZS) {
            $isShowDetail = false;
        }

        return [
            'list'         => $list,
            'count'        => $paginator->total(),
            'pageNum'      => $pageNum,
            'pageSize'     => $pageSize,
            'isShowDetail' => $isShowDetail,
        ];
    }

    /**
     * @throws GuzzleException
     */
    public static function checkFormRequired($siteId, $rmsUserId, $rmsUserName): array
    {
        $validateRes             = [];
        $siteLocationFormContent = self::getSiteFormContent($siteId);
//        return $siteLocationFormContent;
        $baseFieldsValidate = function () use ($siteLocationFormContent, &$validateRes) {
            collect($siteLocationFormContent)->each(function ($moduleFormContent) use (&$validateRes) {
                if (in_array($moduleFormContent["key"], ["complementary", "competingGoods", "customers"])) {
                    if (
                        in_array($moduleFormContent["key"], ["complementary", "competingGoods"])
                        &&
                        collect($moduleFormContent["value"])->where("isTemplate", "=", false)->count() == 0
                        &&
                        !(SiteLocationService::$siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL && SiteLocationService::$siteLocationModel->openingStatus == SiteLocationEnum::OPENING_STATUS_OFF)
                    ) {
                        array_push($validateRes, [
                            "module"     => $moduleFormContent["key"],
                            "moduleName" => $moduleFormContent["name"],
                            "id"         => 0,
                            "field"      => "",
                            "required"   => true,
                            "text"       => ""
                        ]);
                    } else {
                        collect($moduleFormContent["value"])->where("isTemplate", "=", false)->each(function (
                            $groupProduct
                        ) use (&$validateRes, $moduleFormContent) {
                            $id = $groupProduct["id"];
                            collect($groupProduct["tab1"])->each(function ($fieldConfig) use (
                                &$validateRes,
                                $moduleFormContent,
                                $id
                            ) {
                                if ($fieldConfig["required"] && empty($fieldConfig["value"])) {
                                    array_push($validateRes, [
                                        "module"     => $moduleFormContent["key"],
                                        "moduleName" => $moduleFormContent["name"],
                                        "id"         => $id,
                                        "field"      => $fieldConfig["field"],
                                        "required"   => $fieldConfig["required"],
                                        "text"       => $fieldConfig["text"]
                                    ]);
                                }
                            });
                        });
                    }
                } else {
                    collect($moduleFormContent["value"])->each(function ($bottomModuleFormContent) use (
                        &$validateRes,
                        $moduleFormContent
                    ) {
                        collect($bottomModuleFormContent["value"])->each(function ($fieldConfig) use (
                            &$validateRes,
                            $moduleFormContent
                        ) {
                            if ($fieldConfig["required"]) {
                                $required = false;
                                switch ($fieldConfig["input"]) {
                                    case "radio";
                                        if (
                                            !in_array(
                                                $fieldConfig["value"],
                                                array_column($fieldConfig["options"], "value")
                                            ) && $fieldConfig["field"] != 'belongFloor'
                                        ) {
                                            $required = true;
                                        }
                                        break;
                                    case "number":
                                        if (!strlen($fieldConfig["value"])) {
                                            $required = true;
                                        }
                                        break;
                                    default:
                                        if (empty($fieldConfig["value"])) {
                                            $required = true;
                                        }
                                        break;
                                }

                                if ($required) {
                                    array_push($validateRes, [
                                        "module"     => $moduleFormContent["key"],
                                        "moduleName" => $moduleFormContent["name"],
                                        "id"         => 0,
                                        "field"      => $fieldConfig["field"],
                                        "required"   => $fieldConfig["required"],
                                        "text"       => $fieldConfig["text"]
                                    ]);
                                }
                            }
                        });
                    });
                }

            });
        };
        $baseFieldsValidate();
//        return $validateRes;

        $siteLocationModel = self::$siteLocationModel;
        $siteInfo = OpenShopSiteLocationModel::query()->where('id', $siteId)->first();
        //省总
        $userId = (new OpenShopOrganizationManageModel())->getOrganizationManageId($siteInfo->provinceCode, $siteInfo->cityCode, 1);
        // 校验通过
        if (empty($validateRes)) {
//            if (empty($customerAnalysisMapping)) {
//                throw new ResponseHttpException(BaseErrorCode::$LOCATION_CUSTOMER_ANALYSIS_MUST_EXISTS);
//            }

            //新增提交记录
            (new OpenShopSiteLocationExamineLogModel([
                'source'       => OpenShopSiteLocationExamineLogModel::SOURCE_SITE_FROM_SUBMIT,
                'orderNo'      => $siteInfo->orderNo,
                'content'      => '提交表单',
                'position'     => OpenShopSiteLocationExamineLogModel::POSITION_OTHER_EXAMINE,  // 总部负责人
                'isToStore'    => 0,
                'status'       => OpenShopSiteLocationExamineLogModel::STATUS_OK,
                'createdByUid' => $rmsUserId,
                'updatedByUid' => $rmsUserId,
                'isDeleted'    => 1,
            ]))->addData();

            //判断是否为重点城市
            //获得配置的重点城市
            // $keyPointCity = ProgrammingService::hotCity()['hotCity'] ?? [];
            // $judgeFunction = function ($address) use ($keyPointCity){
            //     foreach ($keyPointCity as $city) {
            //         if (strpos($address, $city) !== false) {
            //             return true;
            //         }
            //     }
            //     return false;
            // };
            //$keyPoint = $judgeFunction($siteInfo->cityArea);

            switch ($siteLocationModel->source) {
                case OpenShopSiteLocationModel::SOURCE_OPEN_SHOP:
                    //获得已审批的数量
                    $okCount = OpenShopSiteLocationExamineLogModel::getStatusOkCount($siteInfo->orderNo);

                    switch ($okCount) {
                        case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_4:
                            // 只剩总部负责人审批
                            $siteStatus  = OpenShopSiteLocationModel::SITE_STATUS_11;
                            $pushUserIds = ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
                            $title       = '审核';
                            $content     = '选址表单待审核';
                            break;
                        case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_3:
                            // 给核查专员发送消息
                            $siteStatus = OpenShopSiteLocationModel::SITE_STATUS_2;
                            $title      = '核实';
                            $content    = '选址信息待核实';

                            // 获得审批的人的UserId
                            $pushUserIds = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL);

                            break;
                        case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2:
                            // 给选址负责人发送消息
                            $siteStatus = OpenShopSiteLocationModel::SITE_STATUS_2;
                            $title      = '审批';
                            $content    = '选址表单待审批';

                            // 获得审批的人的UserId
                            $pushUserIds = ConfigModel::getManager(ConfigModel::SITE_MANAGER);

                            break;
                        case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1:
                            // 判断还没有审批的那一个人发送消息
                            $siteStatus = OpenShopSiteLocationModel::SITE_STATUS_2;
                            $title      = '审批';
                            $content    = '选址表单待审批';

                            // 获得审批职位信息
                            $auditPosition = (int)OpenShopSiteLocationExamineLogModel::query()
                                ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK)
                                ->value('position');

                            // 简单一点判断是否为战区负责人
                            if ($auditPosition == OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER) {
                                // 省总审批
                                $pushUserIds = [$userId];
                            } else {
                                // 战区总审批
                                $pushUserIds = [OpenShopRegionManageModel::getWarZoneInfoByProvinceCode($siteInfo->provinceCode)['userId'] ?? 0];
                            }
                            break;
                        default:
                            $siteStatus = OpenShopSiteLocationModel::SITE_STATUS_2;
                            $title      = '审批';
                            $content    = '选址表单待审批';

                            // 给省总和战区负责人发消息
                            $pushUserIds = array_unique(array_merge([$userId, (OpenShopRegionManageModel::getWarZoneInfoByProvinceCode($siteInfo->provinceCode)['userId'] ?? 0)]));
                    }

                    //更新主表状态
                    OpenShopSiteLocationModel::query()
                                             ->where('id', $siteId)
                                             ->update([
                                                 'siteStatus'          => $siteStatus,
                                                 "houseEvaluateStatus" => SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH,
                                                 "updatedByUid"        => $rmsUserId,
                                                 "handler"             => implode(',', $pushUserIds)
                                             ]);

                    // 发送飞书推送
                    $noticeServer = new NoticeService($siteInfo->orderNo, $rmsUserId);
                    $noticeServer->setMissionDealUserInfo($userId);
                    $noticeServer->setPushUserInfos($pushUserIds);
                    $noticeServer->setMissionContent($content);
                    $noticeServer->siteLocationAuditJob($title);
                    //幂等
                    $replayCount = OpenShopSiteLocationReplayModel::query()
                                                                  ->where('createdByUid', $rmsUserId)
                                                                  ->where('orderNo', $siteInfo->orderNo)
                                                                  ->count();
                    if (!$replayCount) {
                        OpenShopSiteLocationReplayModel::query()->create([
                            'content'      => '',
                            'orderNo'      => $siteInfo->orderNo,
                            'createdByUid' => $rmsUserId,
                            'updatedByUid' => $rmsUserId,
                        ]);
                    }
                    break;
                case OpenShopSiteLocationModel::SOURCE_HOUSING:
                    if (in_array($siteInfo->clueStatus, [OpenShopSiteLocationModel::CLUE_STATUS_3, OpenShopSiteLocationModel::CLUE_STATUS_11])) {
                        break;
                    }
                    $siteManager = ConfigModel::getManager(ConfigModel::SITE_MANAGER);
                    if (self::isSolicitBusinessManager($siteLocationModel->createdByUid)) {
                        $approveProcedure =  OpenShopSiteLocationExamineLogModel::APPROVE_PROCEDURE["solicitBusinessManagerApprove"];
                        $existsApproveCount = OpenShopSiteLocationExamineLogModel::getExistsApproveCount($siteLocationModel->orderNo);
                        $handlerArr = OpenShopSiteLocationExamineLogModel::getApproveProcedureUser($approveProcedure[$existsApproveCount], $siteLocationModel);
                        $rejectFunc = function () use ($siteLocationModel, $approveProcedure, $existsApproveCount, $handlerArr) {
                            $msgSupport = FeishuMsgSupport::getInstance(
                                "您有一条房源待审核！",  $handlerArr);

                            $msgSupport->setContent(
                                ["name" => "房源所在区域", "value" => $siteLocationModel->cityArea],
                                ["name" => "任务名称", "value" => "房源审核"],
                                ["name" => "任务创建时间", "value" => formatDate(time())],
                            )->msgSend(["path" => "pages/house-source/add-source?id={$siteLocationModel->id}"]);
                        };

                        if ($existsApproveCount < count($approveProcedure)) {
                            $rejectFunc();
                        }
                    } else {
                        //$customerDevelop = KmsUser::query()->where('rootDepartmentName', '选址开发中心')->where('rmsUserId', $siteLocationModel->developConsultantId)->exists();
                        $customerDevelop = false;
                        if ($customerDevelop) {
                            $handlerArr = SiteLocationAuditService::getNextAuditWithHouse($siteLocationModel);
                        } else {
                            // 固定是省总
                            $handlerArr = [$userId];
                        }
                        FeishuMsgSupport::getInstance("您有一条房源待审核！", $handlerArr)
                            ->setContent(
                                ["name" => "房源所在区域", "value" => $siteLocationModel->cityArea],
                                //["name" => "任务处理角色", "value" => "省区负责人"],  //会签流程  角色不能写死
                                ["name" => "任务名称", "value" => "房源审核"],
                                //["name" => "任务处理人", "value" => $provinceInfoBy["operationName"] ?? ""],
                                ["name" => "任务创建时间", "value" => formatDate(time())],
                            )->msgSend(["path" => "pages/house-source/add-source?id={$siteId}"]);
                    }
                    OpenShopSiteLocationModel::query()->where("id", $siteId)->update([
                        "clueStatus"          => OpenShopSiteLocationModel::CLUE_STATUS_11,
                        "updatedAt"           => time(),
                        "houseEvaluateStatus" => SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH,
                        "updatedByUid"        => AppletAuth::$userInfo->userId,
                        "handler"             => implode(',', $handlerArr),
                    ]);
                    break;
            }
        }

        return self::arrayUnique($validateRes, 'field');
    }


    public static function arrayUnique($requiredArr, $unique_key)
    {
        $tmp_key[] = array();
        foreach ($requiredArr as $key => &$item) {
            if (is_array($item) && isset($item[$unique_key])) {
                if (in_array($item[$unique_key], $tmp_key)) {
                    unset($requiredArr[$key]);
                } else {
                    $tmp_key[] = $item[$unique_key];
                }
            }
        }
        //重置一下二维数组的索引
        return array_slice($requiredArr, 0, count($requiredArr), false);
    }

    /**
     * @param string $field
     * @param string|array $value
     * @return mixed
     */
    public static function getSiteLocationField(
        string $field,
        $value = "",
        $oldValue = null
    ) {
        if ($field == 'lineMarking') {
            //获得动线标注文件
            $value = ResourcesModel::query()
                ->where('businessId', self::$siteLocationModel->id)
                ->where('business', ResourcesModel::BUSINESS_MOVING_LING_MARKING_DESC)
                ->where('module', ResourcesModel::MODULE_TYPE_MOVING_LING_MARKING_DESC)
                ->where('name', 'lineMarking')  //动线标注
                ->get()
                ->map(function (ResourcesModel $resourcesModel) {
                    return json_decode($resourcesModel->extra);
                })->toArray();
        }
        return self::$siteLocationFormEnum->getSiteLocationField($field, $value, 0, $oldValue);
    }

    public static function handleBaseRequired($info, $i, $requiredArr): array
    {
        foreach ($info as $key => $value) {
            $enumInfo = self::getSiteLocationField($key);


            $isCouldZeroField = in_array($key, SiteLocationEnum::COULD_ZERO_FIELDS);
            if (
                isset($enumInfo['required']) &&
                $enumInfo['required'] &&
                (($isCouldZeroField && strlen($value) == 0) || (empty($value) && !$isCouldZeroField))
            ) {
                $requiredArr[$i]['field']    = $enumInfo['field'];
                $requiredArr[$i]['required'] = $enumInfo['required'];
                $requiredArr[$i]['text']     = $enumInfo['text'];
                $i++;
            }
        }


        return ['requiredArr' => $requiredArr, 'i' => $i];
    }

    public static function handleCustomerFileRequired(
        $customerAnalysisMapping,
        $i,
//        SiteLocationFormEnum $siteLocationEnum,
        $requiredArr
    ) {
//        if (empty($customerAnalysisMapping->toArray())) {
//            $requiredArr[$i]['field']    = 'customer';
//            $requiredArr[$i]['required'] = 'required';
//            $requiredArr[$i]['text']     = '客群分析';
//            $i++;
//        }
        foreach ($customerAnalysisMapping as $key => &$value) {
            unset($value['id']);
            unset($value['orderNo']);
            unset($value['siteId']);
            unset($value['isDeleted']);
            unset($value['createdAt']);
            unset($value['createdByUid']);
            unset($value['updatedAt']);
            unset($value['updatedByUid']);
            unset($value['updatedByUid']);
            $value = $value->toArray();
            unset($value['file_rel']);
            foreach ($value as $item => $items) {
                $enumInfo = self::getSiteLocationField($item);
                if ($enumInfo['required'] && empty($items)) {
                    $requiredArr[$i]['field']    = $enumInfo['field'];
                    $requiredArr[$i]['required'] = $enumInfo['required'];
                    $requiredArr[$i]['text']     = $enumInfo['text'];
                    $i++;
                }
            }
        }
        return ['requiredArr' => $requiredArr, 'i' => $i];
    }

    public static function validateSubmitCompetingProduct(SiteLocationFormEnum $siteLocationEnum, array &$requiredArr)
    {
        if (
            self::$siteLocationModel->productAnalysisRel
            &&
            $competingProduct = self::$siteLocationModel
                ->productAnalysisRel
                ->where("type", OpenShopSiteLocationProductAnalysisModel::TYPE_1)
        ) {
            $competingProductForm = SiteLocationFormEnum::competingProductAnalyse(self::$siteLocationModel);

//            if($siteLocationEnum->getSiteLocationField())

        } else {
            array_push($requiredArr, [
                'module'   => 'competingProductAnalyse',
                'field'    => 'product',
                'required' => 'required',
                'text'     => '竞品/互补品'
            ]);
        }
    }


    public static function handleProductMappingRequired(
        $productAnalysisRelMapping,
        $i,
        $siteLocationEnum,
        $requiredArr
    ) {
        if (empty($productAnalysisRelMapping->toArray())) {
            $requiredArr[$i]['module']   = 'productAnalyse';
            $requiredArr[$i]['field']    = 'product';
            $requiredArr[$i]['required'] = 'required';
            $requiredArr[$i]['text']     = '竞品/互补品';
            $i++;
        } else {
            foreach ($productAnalysisRelMapping as $key => $value) {
                unset($value['id']);
                unset($value['orderNo']);
                unset($value['siteId']);
                unset($value['isDeleted']);
                unset($value['createdAt']);
                unset($value['createdByUid']);
                unset($value['updatedAt']);
                unset($value['updatedByUid']);
                unset($value['updatedByUid']);
                $fileList       = $value['fileRel'];
                $productFileRes = UploadFileResourceEnum::handleFileRes($fileList,
                    UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST);
                if (
                    empty($productFileRes) ||
                    !isset($productFileRes[UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST[UploadFileResourceEnum::PRODUCT_SHOP_INNER_PHOTO]])
                ) {
                    $requiredArr[$i]['module']   = 'productAnalyse';
                    $requiredArr[$i]['field']    = UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST[UploadFileResourceEnum::PRODUCT_SHOP_INNER_PHOTO];
                    $requiredArr[$i]['required'] = 'required';
                    $requiredArr[$i]['text']     = '午时阶段图片';
                    $i++;
                }

                if (
                    empty($value["specialExplanation"])
                    &&
                    empty($productFileRes[UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST[UploadFileResourceEnum::PRODUCT_SHOP_ELEM_PHOTO]])
                    &&
                    empty($productFileRes[UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST[UploadFileResourceEnum::PRODUCT_SHOP_MEITUAN_PHOTO]])
                ) {
                    $requiredArr[$i]['module']   = 'productAnalyse';
                    $requiredArr[$i]['field']    = "specialExplanation";
                    $requiredArr[$i]['required'] = 'required';
                    $requiredArr[$i]['text']     = '外卖特殊备注';
                    $i++;
                }

                $value = $value->toArray();
                unset($value['file_rel']);
                $type = $value['type'];
                unset($value['type']);
                foreach ($value as $item => $items) {
                    $enumInfo = $siteLocationEnum->getSiteLocationField($item . $type);
                    if ($enumInfo['required'] && empty($value)) {
                        $requiredArr[$i]['field']    = $enumInfo['field'];
                        $requiredArr[$i]['required'] = $enumInfo['required'];
                        $requiredArr[$i]['text']     = $enumInfo['text'];
                        $i++;
                    }
                }
            }
        }

        return ['requiredArr' => $requiredArr, 'i' => $i];
    }

    public static function handleUploadFildRequired(
        $uploadFileResourceRel,
        $i,
        $siteLocationEnum,
        $requiredArr
    ) {
        if (empty($uploadFileResourceRel->toArray())) {
            $requiredArr[$i]['field']    = 'uploadFile';
            $requiredArr[$i]['required'] = false;
            $requiredArr[$i]['text']     = '带星的图片/视频';
            $i++;
        } else {
            $haveFile = [];
            foreach ($uploadFileResourceRel as $value) {
                $haveFile[] = $value->position;
            }
            if (self::$siteLocationModel->source == OpenShopSiteLocationModel::SOURCE_HOUSING) {
                if (in_array(self::$siteLocationModel->siteType, [
                        SiteLocationEnum::SITE_TYPE_18,
                        SiteLocationEnum::SITE_TYPE_1,
                        SiteLocationEnum::SITE_TYPE_2,
                        SiteLocationEnum::SITE_TYPE_3,
                        SiteLocationEnum::SITE_TYPE_4
                    ]) && !in_array(UploadFileResourceEnum::MOVING_LING_MARKING, $haveFile)) {
                    $requiredArr[$i]['field']    = 'uploadFile';
                    $requiredArr[$i]['required'] = false;
                    $requiredArr[$i]['text']     = '带星的图片/视频';
                    $i++;
                } else {
                    $requiredResourcePositions = [];

                    if (
                        self::$siteLocationModel->handleBusinessLicense == SiteLocationEnum::HANDLE_BUSINESS_LICENSE_YES
                        &&
                        self::$siteLocationModel->historyBusinessLicense == SiteLocationEnum::HISTORY_BUSINESS_LICENSE_YES
                    ) {
                        array_push($requiredResourcePositions, UploadFileResourceEnum::LICENSE_BUSINESS_PHOTO);
                    }

                    if (
                        self::$siteLocationModel->handleFoodLicense == SiteLocationEnum::HANDLE_FOOD_LICENSE_YES
                        &&
                        self::$siteLocationModel->historyFoodLicense == SiteLocationEnum::HISTORY_FOOD_LICENSE_YES
                    ) {
                        array_push($requiredResourcePositions, UploadFileResourceEnum::LICENSE_FOOD_PHOTO);
                    }

                    if (
                        !empty($requiredResourcePositions)
                        &&
                        collect($uploadFileResourceRel ?? [])->whereIn("position", $requiredResourcePositions)
                                                             ->count() != count($requiredResourcePositions)
                    ) {
                        $requiredArr[$i]['field']    = 'uploadFile';
                        $requiredArr[$i]['required'] = false;
                        $requiredArr[$i]['text']     = '带星的图片/视频';
                        $i++;
                    }
                }
            } else {
                $requiredPosition = [
                    UploadFileResourceEnum::PROJECT_MESSAGE_BAIDU_HEAT_MAP,
                    UploadFileResourceEnum::SHOP_ADDRESS_SHOP_VIDEO,
                    UploadFileResourceEnum::SHOP_ADDRESS_LEFT_PHOTO,
                    UploadFileResourceEnum::SHOP_ADDRESS_RIGHT_PHOTO,
                    UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO,
                    UploadFileResourceEnum::SHOP_ADDRESS_SHOP_INNER_PHOTO,
                    UploadFileResourceEnum::SHOP_ADDRESS_PANORAMA_PHOTO,
                ];

                if (in_array(self::$siteLocationModel->siteType, [
                    SiteLocationEnum::SITE_TYPE_18,
                    SiteLocationEnum::SITE_TYPE_1,
                    SiteLocationEnum::SITE_TYPE_2,
                    SiteLocationEnum::SITE_TYPE_3,
                    SiteLocationEnum::SITE_TYPE_4
                ])) {
                    array_push($requiredPosition, UploadFileResourceEnum::MOVING_LING_MARKING);
                }

                if (
                    self::$siteLocationModel->handleBusinessLicense == SiteLocationEnum::HANDLE_BUSINESS_LICENSE_YES
                    &&
                    self::$siteLocationModel->historyBusinessLicense == SiteLocationEnum::HISTORY_BUSINESS_LICENSE_YES
                ) {
                    array_push($requiredPosition, UploadFileResourceEnum::LICENSE_BUSINESS_PHOTO);
                }

                if (
                    self::$siteLocationModel->handleFoodLicense == SiteLocationEnum::HANDLE_FOOD_LICENSE_YES
                    &&
                    self::$siteLocationModel->historyFoodLicense == SiteLocationEnum::HISTORY_FOOD_LICENSE_YES
                ) {
                    array_push($requiredPosition, UploadFileResourceEnum::LICENSE_FOOD_PHOTO);
                }

                if (count(array_intersect($requiredPosition, array_unique($haveFile))) != count($requiredPosition)) {
                    $requiredArr[$i]['field']    = 'uploadFile';
                    $requiredArr[$i]['required'] = false;
                    $requiredArr[$i]['text']     = '带星的图片/视频';
                    $i++;
                }

            }
        }
        return ['requiredArr' => $requiredArr, 'i' => $i];
    }

    public static function delProductAnalysis(
        $id,
        $authInfo
    ) {
        OpenShopSiteLocationProductAnalysisModel::query()
                                                ->where('id', $id)
                                                ->update(['isDeleted' => 1, 'updatedByUid' => $authInfo['userId']]);
    }

    /**
     * 创建房源线索
     *
     * @param object|null $userInfo
     * @param object $clueParams
     * @param object $attachParams
     * @throws Exception
     * @throws GuzzleException
     */
    public static function clueSiteLocationInsert(?object $userInfo, object $clueParams, object $attachParams, int $taskId = 0)
    {
        try {
            DB::beginTransaction();

            $createdByUid = $userInfo ? $userInfo->userId : 0;
            $clueStatus   = OpenShopSiteLocationModel::CLUE_STATUS_1;
            if ($createdByUid) {
                $roleId     = ConfigService::config("openShop", "developmentConsultant")["developmentConsultant"];
                $isRoleUser = RmsUserRemote::isRoleUser($roleId, $createdByUid)["isRoleUser"];
                if ($isRoleUser) {
                    $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_2;
                }
            }

            $levelText = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[($clueParams->cityType ?? 5)] ?? '';

            $standard = GuanyuanDataService::levelCityRentRange($levelText);

            if (($clueParams->clueRent / 100) < $standard['minFourNumber']) {
                $rentGrade = SiteLocationEnum::COST_PERFORMANCE_HIGH;
            } elseif (($clueParams->clueRent / 100) > $standard['maxFourNumber']) {
                $rentGrade = SiteLocationEnum::COST_PERFORMANCE_LOW;
            } else {
                $rentGrade = SiteLocationEnum::COST_PERFORMANCE_MEDIUM;
            }

            if ($clueParams->townGrade === '') {
                $clueParams->townGrade = 0;
            }

            $isMall = false;  //判断是否为商场

            //特殊处理
            $clueParams = (array)$clueParams;
            $clueParams['patternType'] = implode(',', Arr::sort(explode(',', $clueParams['patternType'])));
            $wgNumber = '';
            $wgGrade  = 0;
            if (in_array($clueParams['shopModelType'], [SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_SCHOOL])) {
                $wgNumber = $clueParams['wgNumber'] ?? '';
                $wgGrade  = array_search($clueParams['wgGrade'] ?? '', ProgrammingEnum::GRADE_MAPPING) ?: 0;
            }
            unset($clueParams['wgNumber']);
            unset($clueParams['wgGrade']);
            unset($clueParams['wgMatch']);

            if ($clueParams['shopModelType'] == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
                if (mb_strlen($clueParams['mallId'] ?? '')) {
                    if ($clueParams['isWhiteList']) {
                        $isMall = true;
                        //在白名单中
                        try {
                            $guanyuanData = GuanyuanDataService::getMallDataByMallId($clueParams['mallId'])[0] ?? [];
                        } catch (\Exception $exception) {
                            $guanyuanData = [];
                        }
                        $clueParams['mallProvince']     = $guanyuanData['省份'] ?? '';
                        $clueParams['mallCity']         = $guanyuanData['城市'] ?? '';
                        $clueParams['mallDistrict']     = $guanyuanData['区县'] ?? '';
                        $clueParams['mallArea']         = $guanyuanData['区域'] ?? '';
                        $clueParams['mallAddress']      = $guanyuanData['地址'] ?? '';
                        $clueParams['businessAddress']  = $guanyuanData['地址'] ?? '';
                        $clueParams['businessArea']     = ($guanyuanData['省份'] ?? '') . '-' . ($guanyuanData['城市'] ?? '') . '-' . ($guanyuanData['区县'] ?? '');
                        $clueParams['businessDistrict'] = $guanyuanData['区域'] ?? '';

                        $shopGrade = 0;
                        foreach (OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING as $k => $shopGradeText) {
                            if ($shopGradeText == ($guanyuanData['区域'] ?? '')) {
                                $shopGrade = $k;
                                break;
                            }
                        }
                        $clueParams['shopGrade'] = $shopGrade;

                    } else {
                        //不再白名单中
                        if (!$clueParams['mallStatus']) {
                            //未开业
                            $isMall = true;
                        }
                        $siteLocationMall = SiteLocationMallModel::query()
                                                                 ->where('mallId', $clueParams['mallId'])
                                                                 ->first();

                        if (null != $siteLocationMall) {
                            $clueParams['mallProvince']     = $siteLocationMall->province;
                            $clueParams['mallCity']         = $siteLocationMall->city;
                            $clueParams['mallDistrict']     = $siteLocationMall->district;
                            $clueParams['mallArea']         = $siteLocationMall->area;
                            $clueParams['mallAddress']      = $siteLocationMall->address;
                            $clueParams['businessAddress']  = $siteLocationMall->address;
                            $clueParams['businessArea']     = $siteLocationMall->province . '-' . $siteLocationMall->city . '-' . $siteLocationMall->district;
                            $clueParams['businessDistrict'] = $siteLocationMall->area;
                        }
                    }
                } else {
                    $clueParams['mallId'] = 'MALL-' . time();
                    if (!$clueParams['mallStatus'] && !$clueParams['isWhiteList']) {
                        //未开业
                        $isMall = true;
                    }
                }
            }
            //点位到期时间特殊处理
            if (isset($clueParams['nearbyPlaceholderTime'])) {
                $clueParams['placeholderTime'] = strtotime($clueParams['nearbyPlaceholderTime']);
                unset($clueParams['nearbyPlaceholderTime']);
            }
            $clueParams['fixedRent'] = $clueParams['clueRent'] ?? 0;

            // 产品定价 菜单等级）选址报告中根据城市等级+选址场景自动调用展示
            $getShopAttribute = self::getShopAttributeByGrade($clueParams);
            unset($clueParams['townText']);
            $clueParams['menuLevel']          = $getShopAttribute['menuLevelId'];         // 产品定价 菜单等级
            $clueParams['siteSelectionGrade'] = $getShopAttribute['siteSelectionGradeId'];// 选址场景分级

            $siteLocationId = OpenShopSiteLocationModel::query()->insertGetId(array_merge((array)$clueParams, [
                "source"       => OpenShopSiteLocationModel::SOURCE_HOUSING,
                "clueStatus"   => OpenShopSiteLocationModel::CLUE_STATUS_12,
                "rentGrade"    => $rentGrade,
                "createdAt"    => time(),
                "updatedAt"    => time(),
                "createdByUid" => $createdByUid,
                "updatedByUid" => $createdByUid,
            ], $clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_2 ? [
                "developConsultantName" => $userInfo->username,
                "developConsultantId"   => $createdByUid,
                "handler"               => $createdByUid,
            ] : []));


            if (in_array($clueParams['shopModelType'], [SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_SCHOOL])) {
                // 获得街道的经纬度
                $streetModel = MapNationalStreetModel::query()
                    ->where('wgNumber', $wgNumber)
                    ->select(['lat', 'lng'])
                    ->first();

                $type = OpenShopSiteLocationWangguiRelationModel::TYPE_STREET;

                if ($streetModel != null) {
                    // 判断是否存在社区网规
                    $communityModel = MapNationalCommunityModel::query()
                        ->where('lat', $streetModel->lat)
                        ->where('lng', $streetModel->lng)
                        ->first();
                    if ($communityModel != null) {
                        $type     = OpenShopSiteLocationWangguiRelationModel::TYPE_COMMUNITY;
                        $wgNumber = $communityModel->wgNumber;
                    }
                }

                $relationWangguiModel               = new OpenShopSiteLocationWangguiRelationModel();
                $relationWangguiModel->siteId       = $siteLocationId;
                $relationWangguiModel->wgNumber     = $wgNumber;
                $relationWangguiModel->grade        = $wgGrade;
                $relationWangguiModel->match        = strlen($wgNumber) ? OpenShopSiteLocationWangguiRelationModel::MATCH_ON : OpenShopSiteLocationWangguiRelationModel::MATCH_OFF;
                $relationWangguiModel->type         = $type;
                $relationWangguiModel->createdByUid = $createdByUid;
                $relationWangguiModel->updatedByUid = $createdByUid;
                $relationWangguiModel->save();
            }


            if ($isMall) {
                $params = [
                    'orderNo'             => "FY" . $siteLocationId,
                    'clueStatus'          => $clueStatus,
                    'houseEvaluateStatus' => SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH,
                ];
            } else {
                $params = [
                    'orderNo'  => "FY" . $siteLocationId,
                ];
            }
            if ($clueParams['shopModelType'] != SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
                $params = array_merge($params, ['mallName' => '']);
            }

            OpenShopSiteLocationModel::query()->where("id", $siteLocationId)->update($params);

            if ($isMall) {
                //推动后续流程
                (new SiteLocationInputService("FY" . $siteLocationId, $userInfo->userId))->fsHouseClue();
            }

            if ($clueParams['shopModelType'] != SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
                // 房源评估表单初始化
                (new SiteLocationInputService("FY" . $siteLocationId))->initOrderInput();
            }
            $background = '';
            //todo 附件入库
            OpenShopUploadFileResourceModel::query()->insert(collect((array)$attachParams)->map(function ($v) use (
                $siteLocationId,
                &$background
            ) {
                //不要热力图 删除缓存文件
                @unlink($v['tempFilePath']);
                //$background = $v['tempFilePath'];
                unset($v['tempFilePath']);
                $v["orderNo"]  = "FY" . $siteLocationId;
                $v["isPublic"] = 1;
                return $v;
            })->toArray());

            // 添加勘址任务于房源的绑定关系
            if ($taskId) {
                CustomerDepartmentSiteLocationRelationModel::query()
                    ->insert([
                        [
                            'taskId'         => $taskId,
                            'source'         => OpenShopSiteLocationModel::SOURCE_HOUSING,
                            'relationNumber' => "FY" . $siteLocationId,
                            'relationId'     => $siteLocationId,
                            'createdAt'      => time(),
                            'updatedAt'      => time(),
                            'createdByUid'   => $createdByUid,
                            'updatedByUid'   => $createdByUid,
                        ]
                    ]);


                CustomerDepartmentOperationLogModel::addLog($taskId, '关联房源', [
                    [
                        'theme' => '关联房源',
                        'data'  => [
                            [
                                'key'         => 'orderNo',
                                'beforeValue' => '',
                                'afterValue'  => "FY" . $siteLocationId,
                                'beforeText'  => '',
                                'afterText'   => "FY" . $siteLocationId,
                                'type'        => 1,
                                'description' => '编号变更',
                            ]
                        ]
                    ]
                ], $createdByUid);
            }

            try {
                //获得外卖预估
                $distance = 3;    //默认3km
                // 外卖预估数据
                $takeOutData = (new WaiMaiAnalysisService())
                    ->setLngLat($clueParams['longitude'], $clueParams['latitude'], $distance);
                $estimate    = $takeOutData->calcEstimateData();
                $takeOutInfo = [
                    'doublePlatformSales'  => (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2),
                    'doublePlatformInCome' => ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30),
                    'mtSales'              => (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2),
                    'elmSales'             => (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2),
                ];
                WangguiDotWaimaiEstimateModel::query()->insert(
                    array_merge($takeOutInfo, [
                        'orderNo' => $params['orderNo'],
                        'lng'     => $clueParams['longitude'],
                        'lat'     => $clueParams['latitude'],
                    ])
                );
            } catch (\Exception $exception) {}

            DB::commit();

            //上传热力图处理
            //if (strlen($background)) event(new GenerateHeatMapImageEvent($clueParams['longitude'], $clueParams['latitude'], $background, $siteLocationId));

            return [
                'orderNo' => 'FY' . $siteLocationId,
                'id'      => $siteLocationId
            ];

        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }
    }

    /**
     * 房源线索详情
     *
     * @param int $id
     * @return array|void
     * @throws GuzzleException
     * @throws Exception
     */
    public static function getClueSiteLocationDetail(int $id, $userInfo, $power)
    {
        try {
            $siteLocations = OpenShopSiteLocationModel::query()
                                                      ->whereIn('source',
                                                          [
                                                              OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                              OpenShopSiteLocationModel::SOURCE_HOUSING
                                                          ])
                                                      ->with([
                                                          "attachRel" => function ($query) {
                                                              $query->whereIn("position",
                                                                  array_keys(UploadFileResourceEnum::CLUE_SITE_LOCATION_MAP))
                                                                    ->where("isDeleted", 0);
                                                          }
                                                      ])->where("id", $id)->first();
            if (null == $siteLocations) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '线索不存在');
            }
            try {
                //更新附近预占点位
                $siteLocations = (new SiteLocationInputService($siteLocations->orderNo))->updateNearbyPlaceHolder();
            } catch (\Exception $exception) {

            }

            $remark = "";
            if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_4) {
                $log    = OpenShopSiteLocationExamineLogModel::query()
                                                             ->where("source",
                                                                 OpenShopSiteLocationModel::SOURCE_HOUSING)
                                                             ->where("orderNo", $siteLocations->orderNo)
                                                             ->where("status",
                                                                 OpenShopSiteLocationExamineLogModel::STATUS_REFUSE)
                                                             ->orderByDesc("id")
                                                             ->first();
                $remark = $log ? $log->content : "";
            }

            $refereeUids                       = $siteLocations->createdByUid > 0 ? [$siteLocations->createdByUid] : [];
            $rmsUserInfo                       = (object)(empty($refereeUids) ? [] : RmsUserRemote::getRmsUserByIds($refereeUids));
            $rmsUserInfoCollection             = collect($rmsUserInfo)->keyBy("id");
            ClueSiteLocationResource::$rmsUser = $rmsUserInfoCollection;

            $provinceManager    = OrganizationManageService::getProvinceInfoByProvinceCode($siteLocations->provinceCode);
            $provinceManagerUid = $provinceManager["operationUid"] ?? 0;

            $siteManager              = ConfigModel::getManager(ConfigModel::SITE_MANAGER);
            $isSolicitBusinessManager = self::isSolicitBusinessManager($siteLocations->createdByUid);

            //获取审批流
            if ($isSolicitBusinessManager) {
                $approveProcedure = OpenShopSiteLocationExamineLogModel::APPROVE_PROCEDURE["solicitBusinessManagerApprove"];
            } else {
                //选址2.2.1 省总审批
                $approveProcedure = [
                    OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE
                ];
            }

            $existsApproveCount = OpenShopSiteLocationExamineLogModel::query()
                                                                     ->where('orderNo', $siteLocations->orderNo)
                                                                     ->where("type", 0)
                                                                     ->where('status',
                                                                         OpenShopSiteLocationExamineLogModel::STATUS_OK)
                                                                     ->count();

            $approverName = "-";
            //房源或者自带址 自动获取下一级流程审批人
            if ($existsApproveCount < count($approveProcedure) && $siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11) {
//                $nowApproveProcedure = $approveProcedure[$existsApproveCount];
//                $approveProcedureUserIds = OpenShopSiteLocationExamineLogModel::getApproveProcedureUser($nowApproveProcedure, $siteLocations);
//                $approverName = implode(',',
//                    array_column(RmsUserRemote::getRmsUserByIds($approveProcedureUserIds), 'username'));
                //获取处理人
                if (mb_strlen($siteLocations->handler)) {
                    $approverNameArr = RmsUserRemote::getRmsUserByIds(explode(',', $siteLocations->handler), ['username']);
                    $approverName    = implode(',', collect($approverNameArr)->pluck('username')->toArray());
                }
            }

            // 大客户部自动获取下一阶段处理人
            // 判断是否是大客户开发部
            //$customerDevelop = KmsUser::query()->where('rootDepartmentName', '选址开发中心')->where('rmsUserId', $siteLocations->developConsultantId)->exists();
            $customerDevelop = false;
            if ($customerDevelop &&  $siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11) {
                // 下一个阶段审批人
                $nextAudit = SiteLocationAuditService::getNextAuditWithHouse($siteLocations);
                $approverNameArr = RmsUserRemote::getRmsUserByIds($nextAudit, ['username']);
                $approverName    = implode(',', collect($approverNameArr)->pluck('username')->toArray());
            }


//            if ($isSolicitBusinessManager) {
//                $siteManager = array_unique(array_merge($siteManager,
//                    ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN)));
//            }
//
//            $approverName = (function (int $clueStatus) use ($siteManager) {
//                $approverName = "-";
//                if ($clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11) {
//                    $approverName = implode(',',
//                        array_column(RmsUserRemote::getRmsUserByIds($siteManager), 'username'));
//                }
//                return $approverName;
//            })($siteLocations->clueStatus);
//            $isShowAssessButton = false;
//            if ($siteLocations->shopModelType) { //要判断是历史数据  已当前新加的必填字段『shopModelType』作为依据
//                if (in_array($siteLocations->clueStatus, [OpenShopSiteLocationModel::CLUE_STATUS_2, OpenShopSiteLocationModel::CLUE_STATUS_0])) {
//                    $isShowAssessButton = true;
//                }
//            }
            $isShowSiteButton   = false;
            $isNextButton       = false;
            $siteButtonText     = '查看选址评估';
            $isProvinceManager  = false;
            $isLoseEfficacy     = false;  //房源线索失效
            $isDelete           = false;  //房源线索删除
            $loseEfficacyText   = '';     //房源线索失效
            $isUpdateBehaviour  = false;  //是否可以修改
            $isShowAssessButton = false;  //是否可以修改
            $isMakeOverButton   = false;  //是否展示转让按钮
            //开发
            if ($userInfo['userId'] == $siteLocations->developConsultantId) {
                //对自己展示查看
                $isShowSiteButton = true;
                //对自己展示填写
                if (in_array($siteLocations->clueStatus,
                    [OpenShopSiteLocationModel::CLUE_STATUS_2, OpenShopSiteLocationModel::CLUE_STATUS_4])) {
                    $siteButtonText = '填写选址评估';
                }
                if ($siteLocations->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && in_array($siteLocations->siteStatus,
                        [
                            OpenShopSiteLocationModel::SITE_STATUS_0,
                            OpenShopSiteLocationModel::SITE_STATUS_1,
                            OpenShopSiteLocationModel::SITE_STATUS_3
                        ])) {
                    $siteButtonText = '填写选址评估';
                }
                if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_0,
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13
                ])) {
                    $isShowSiteButton = false;
                }
                if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_1,
                    OpenShopSiteLocationModel::CLUE_STATUS_2,
                    OpenShopSiteLocationModel::CLUE_STATUS_4,
                    OpenShopSiteLocationModel::CLUE_STATUS_11
                ])) {
                    $isLoseEfficacy = true;
                    $isDelete       = true;
                }
                if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_12) {
                    $isNextButton = true;
                }
                if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                    $isMakeOverButton = true;
                }
                if (in_array($siteLocations->clueStatus, [OpenShopSiteLocationModel::CLUE_STATUS_12, OpenShopSiteLocationModel::CLUE_STATUS_13])) {
                    $isDelete         = true;
                }
            }

//            if (in_array($userInfo['userId'], $siteManager) && in_array($siteLocations->clueStatus, [
//                    OpenShopSiteLocationModel::CLUE_STATUS_1,
//                    OpenShopSiteLocationModel::CLUE_STATUS_2,
//                    OpenShopSiteLocationModel::CLUE_STATUS_4,
//                    OpenShopSiteLocationModel::CLUE_STATUS_12,
//                    OpenShopSiteLocationModel::CLUE_STATUS_13,
//                ])) {
//                $isLoseEfficacy   = true;
//                $loseEfficacyText = '失效';
//            }

            if (!in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13
                ]) && $siteLocations->shopModelType) {
                $isShowAssessButton = true;
            }


            if ($userInfo['userId'] == $siteLocations->createdByUid && in_array($siteLocations->clueStatus,
                    [OpenShopSiteLocationModel::CLUE_STATUS_4, OpenShopSiteLocationModel::CLUE_STATUS_12])) {
                $isUpdateBehaviour  = true;
                $isNextButton       = true;
                $isShowAssessButton = false;
            }

            if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13
                ]) && $userInfo['userId'] == $siteLocations->createdByUid) {
                $isNextButton     = true;
                $isDelete         = true;
            }

//            if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_2 && $userInfo['userId'] == $siteLocations->createdByUid) {
//                $isLoseEfficacy   = true;
//                $loseEfficacyText = '失效';
//            }
            if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_13 && in_array($userInfo['userId'],
                    $siteManager)) {
                $isNextButton = true;
            }

            //主要处理 [isAll == true] 时的查看选址报告
            if ($power['isAll'] || $userInfo['userId'] == $provinceManagerUid) {
                if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_3,
                    OpenShopSiteLocationModel::CLUE_STATUS_11,
                    OpenShopSiteLocationModel::CLUE_STATUS_5,
                    OpenShopSiteLocationModel::CLUE_STATUS_10,
                    OpenShopSiteLocationModel::CLUE_STATUS_6,
                ])) {
                    $isShowSiteButton = true;
                }
                if ($siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                    $isMakeOverButton = true;
                }
                if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_1,
                    OpenShopSiteLocationModel::CLUE_STATUS_2,
                    OpenShopSiteLocationModel::CLUE_STATUS_4,
                    OpenShopSiteLocationModel::CLUE_STATUS_11
                ])) {
                    $isLoseEfficacy = true;
                    $isDelete       = true;
                }
                if (in_array($siteLocations->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13
                ])) {
                    $isDelete       = true;
                }
            }

            if (($userInfo['userId'] == $provinceManagerUid || in_array($userInfo['userId'],
                        $siteManager)) && $siteLocations->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_1) {
                $isProvinceManager = true;
            }

            $updatedBy = collect(RmsUserRemote::getRmsUserByIds([$siteLocations->updatedByUid],
                ['id', 'username'], false))->first();
            return [
                "detail"                => ClueSiteLocationResource::collection([$siteLocations])
                                                                   ->getIterator()
                                                                   ->current(),
                "approverName"          => $approverName,
                "isProvinceManager"     => $isProvinceManager,
                "isManager"             => $siteLocations->developConsultantId > 0 && $siteLocations->developConsultantId == AppletAuth::$userInfo->userId,
                "remark"                => $remark,
                "isShowAssessButton"    => $isShowAssessButton,
                "approval"              => self::getApprovalRecord($siteLocations->orderNo),
                'isBelongToYourself'    => AppletAuth::$userInfo->userId == $siteLocations->createdByUid,
                'isShowSiteButton'      => $isShowSiteButton,
                'isMakeOverButton'      => $isMakeOverButton,  //是否展示转让按钮
                'siteButtonText'        => $siteButtonText,
                'isNextButton'          => $isNextButton,
                'isLoseEfficacy'        => $isLoseEfficacy,
                'isDelete'              => $isDelete,
                'loseEfficacyText'      => $loseEfficacyText,
                'isUpdateBehaviour'     => $isUpdateBehaviour,
                'developConsultantName' => $siteLocations->developConsultantName,
                'updatedBy'             => $updatedBy['username'] ?? '',
                'updatedAt'             => date('y-m-d H:i:s', $siteLocations->updatedAt->timestamp)
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }


    /**
     * 房源线索详情
     *
     * @param int $id
     * @return array|void
     * @throws Exception
     */
    public static function allClueDetail(int $id)
    {
        try {
            $siteLocations = OpenShopSiteLocationModel::query()->with([
                "attachRel",
                "customerAnalysisRel"           => function ($query) {
                    $query->with("fileRel");
                },
                "competingProductsAnalysisRel"  => function ($query) {
                    $query->where("type", OpenShopSiteLocationProductAnalysisModel::TYPE_1)->with("fileRel");
                },
                "complementProductsAnalysisRel" => function ($query) {
                    $query->where("type", OpenShopSiteLocationProductAnalysisModel::TYPE_2)->with("fileRel");
                }
            ])->where("id", $id)->first();


            return [
                "detail" => AllClueSiteLocationDetailResource::collection([$siteLocations])->getIterator()->current(),
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }


    /**
     * @param object|null $userInfo
     * @param int $id
     * @param int $managerId
     * @param string $managerName
     * @throws Exception|GuzzleException
     */
    public static function assignManager(?object $userInfo, int $id, int $managerId, string $managerName)
    {
        try {
            $siteLocation = OpenShopSiteLocationModel::query()->where("id", $id)->first();

            OpenShopSiteLocationModel::query()->where("id", $id)->update([
                "clueStatus"            => OpenShopSiteLocationModel::CLUE_STATUS_2,
                "updatedAt"             => time(),
                "updatedByUid"          => $userInfo ? $userInfo->userId : 0,
                "developConsultantName" => $managerName,
                "developConsultantId"   => $managerId,
                "handler"               => $managerId
            ]);

            FeishuMsgSupport::getInstance("您有一条房源勘址任务待处理！", [$managerId])
                            ->setContent(
                                ["name" => "房源所在区域", "value" => $siteLocation->cityArea],
                                ["name" => "任务处理角色", "value" => "选址顾问"],
                                ["name" => "任务名称", "value" => "房源线索调查"],
                                ["name" => "任务处理人", "value" => $managerName],
                                ["name" => "任务创建时间", "value" => formatDate(time())],
                            )->msgSend(["path" => "pages/house-source/add-source?id={$id}"]);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @return array|void
     * @throws GuzzleException
     * @throws Exception
     */
    public static function managerList()
    {
        try {
            $roleId       = ConfigService::config("openShop", "developmentConsultant")["developmentConsultant"];
            $managerLists = RmsUserRemote::getRoleUserLists($roleId);
            return ["managerLists" => $managerLists["userLists"]];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 房源线索失效
     *
     * @param object|null $userInfo
     * @param int $id
     * @throws Exception
     */
    public static function clueInvalid(?object $userInfo, int $id, int $type)
    {
        $siteLocationQuery = OpenShopSiteLocationModel::query()->where("id", $id);
        $siteLocationFirst = $siteLocationQuery->first();
        if (null == $siteLocationFirst) {
            throw new ResponseHttpException(10000, null, '该房源不存在');
        }
        switch ($type) {
            case OpenShopSiteLocationModel::HOUSE_OPERATE_TYPE_DELETE:
                if (!in_array($siteLocationFirst->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_12,
                    OpenShopSiteLocationModel::CLUE_STATUS_13,
                    OpenShopSiteLocationModel::CLUE_STATUS_1,
                    OpenShopSiteLocationModel::CLUE_STATUS_2,
                    OpenShopSiteLocationModel::CLUE_STATUS_4,
                    OpenShopSiteLocationModel::CLUE_STATUS_11
                    ])) {
                    throw new ResponseHttpException(10000, null, '该状态不能删除');
                }
                $params = [
                    'isDeleted' => 1,
                ];
                break;
            case OpenShopSiteLocationModel::HOUSE_OPERATE_TYPE_LOSE:
                if (!in_array($siteLocationFirst->clueStatus, [
                    OpenShopSiteLocationModel::CLUE_STATUS_1,
                    OpenShopSiteLocationModel::CLUE_STATUS_2,
                    OpenShopSiteLocationModel::CLUE_STATUS_4,
                    OpenShopSiteLocationModel::CLUE_STATUS_11
                ])) {
                    throw new ResponseHttpException(10000, null, '该状态不能失效');
                }
                $params = [
                    "clueStatus"   => OpenShopSiteLocationModel::CLUE_STATUS_0,
                    "handler"      => '',
                    "updatedAt"    => time(),
                    "updatedByUid" => $userInfo ? $userInfo->userId : 0,
                ];
                break;
            default:
                throw new ResponseHttpException(10000, null, '未知操作类型');
        }
        try {
            $siteLocationQuery->update($params);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 房源线索上下架
     *
     * @param object|null $userInfo
     * @param int $id
     * @param int $type
     * @throws Exception
     */
    public static function clueUpDown(?object $userInfo, int $id, int $type)
    {
        try {
            OpenShopSiteLocationModel::query()->where("id", $id)->update([
                "clueStatus"   => $type,
                "updatedAt"    => time(),
                "updatedByUid" => $userInfo ? $userInfo->userId : 0,
            ]);
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    public static function houseClueList(
        $type,
        $filterValue,
        $filterType,
        $status,
        $provinceCodeUse,
        $pageNum,
        $pageSize,
        $chooses,
        $search,
        $groupBy,
        $grade,
        $rent,
        $area,
        $power,
        $userId,
        $cUid
    ) {
        //我的房源 type=0
        //全部房源 type=1
        //上海分公司--筛选--房源   filterValue  filterType  1-分公司ID  2-省区code
        //房源线索-上架房源-累计成交  status  1 5 6
//        $userId        = 0;
//        $provinceChief = [];
//        if ($scope != PermissionService::PERMISSION_ALL) {
//            if ($scope == PermissionService::PERMISSION_DENY) {
//                return [];
//            }
//            if ($userInfo->position == SiteLocationEnum::POSITION_PROVINCE_CHIEF || $scope == PermissionService::PERMISSION_PROVINCE) {
//                $provinceChief = OrganizationManageService::getProvinceList($userInfo->userId);
//            } else {
//                $userId = $userInfo->userId;
//            }
//
//        }
        if (mb_strlen($status)) {
            $status = explode(',', $status);
        } else {
            $status = [];
        }
        if (in_array(OpenShopSiteLocationModel::CLUE_STATUS_6, $status)) {
            $completed = true;
            //unset($status[array_search(OpenShopSiteLocationModel::CLUE_STATUS_6, $status, false)]);
        } else {
            $completed = false;
        }

        $paginator    = OpenShopSiteLocationModel::query()
                                                 ->when($search, function ($query) use ($search) {
                                                     //区分编号与地址搜索
                                                     if (strpos($search, 'fy') !== false || strpos($search,
                                                             'FY') !== false || strpos($search,
                                                             'Fy') !== false || strpos($search, 'fY') !== false || is_numeric($search)) {
                                                         if (is_numeric($search)) {
                                                             $query->where('id', $search);
                                                         } else {
                                                             $query->where('orderNo', $search);
                                                         }
                                                     } else {
                                                         $query->where(function ($query) use ($search) {
                                                             $query->orWhere('address', 'like', "%$search%")
                                                                   ->orWhere('siteAddress', 'like', "%$search%")
                                                                   ->orWhere('cityArea', 'like', "%$search%");
                                                         });
                                                     }
                                                 })
                                                 ->when(mb_strlen($area), function ($query) use ($area) {
                                                     $area = explode(',', $area);
                                                     $query->where(function ($query) use ($area) {
                                                         foreach ($area as $value) {
                                                             if (is_array(OpenShopSiteLocationModel::HOUSE_AREA_ORM_MAPPING[$value])) {
                                                                 $query->orWhereBetween('area',
                                                                     OpenShopSiteLocationModel::HOUSE_AREA_ORM_MAPPING[$value]);
                                                             } else {
                                                                 $query->orWhere('area', '>',
                                                                     OpenShopSiteLocationModel::HOUSE_AREA_ORM_MAPPING[$value]);
                                                             }

                                                         }
                                                     });
                                                 })
                                                 ->when(mb_strlen($grade), function ($query) use ($grade) {
                                                     $query->whereIn('shopGrade', explode(',', $grade));
                                                 })
                                                 ->when(mb_strlen($rent), function ($query) use ($rent) {
                                                     $rent = explode(',', $rent);
                                                     $query->where(function ($query) use ($rent) {
                                                         foreach ($rent as $value) {
                                                             if (is_array(OpenShopSiteLocationModel::HOUSE_RENT_ORM_MAPPING[$value])) {
                                                                 $query->orWhereBetween('clueRent',
                                                                     OpenShopSiteLocationModel::HOUSE_RENT_ORM_MAPPING[$value]);
                                                             } else {
                                                                 $query->orWhere('clueRent', '>',
                                                                     OpenShopSiteLocationModel::HOUSE_RENT_ORM_MAPPING[$value]);
                                                             }

                                                         }
                                                     });
                                                 })
                                                 ->when(true, function ($query) use ($groupBy) {
                                                     switch ($groupBy) {
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_UNIT_PRICE_ASC:
                                                             $query->addSelect(DB::raw("*, clueRent/area as unitPrice"))
                                                                   ->orderBy('unitPrice');
                                                             break;
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_UNIT_PRICE_DESC:
                                                             $query->addSelect(DB::raw("*, clueRent/area as unitPrice"))
                                                                   ->orderByDesc('unitPrice');
                                                             break;
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_RENT_ASC:
                                                             $query->orderBy('clueRent');
                                                             break;
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_RENT_DESC:
                                                             $query->orderByDesc('clueRent');
                                                             break;
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_AREA_ASC:
                                                             $query->orderBy('area');
                                                             break;
                                                         case OpenShopSiteLocationModel::HOUSE_GROUP_BY_AREA_DESC:
                                                             $query->orderByDesc('area');
                                                             break;
                                                         default:
                                                             $query->orderByDesc('updatedAt');
                                                     }
                                                 })
                                                 ->when(count($status) && $type == OpenShopSiteLocationModel::HOUSE_CLUE_MYSELF,
                                                     function ($query) use ($status) {
                                                         $query->whereIn('clueStatus', $status);
                                                     })
                                                 ->when(!$completed && $type == OpenShopSiteLocationModel::HOUSE_CLUE_MYSELF,
                                                     function ($query) {
                                                         $query->where('source',
                                                             OpenShopSiteLocationModel::SOURCE_HOUSING)
                                                               ->where('bindId',
                                                                   OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE);
                                                     })
                                                 ->where(function ($query) use (
                                                     $userId,
                                                     $chooses,
                                                     $provinceCodeUse,
                                                     $type
                                                 ) {
                                                     $query->when(mb_strlen($provinceCodeUse) && $type == OpenShopSiteLocationModel::HOUSE_CLUE_MYSELF,
                                                         function ($query) use ($provinceCodeUse) {
                                                             $query->where('provinceCode', $provinceCodeUse);
                                                         })
                                                           ->when(mb_strlen($chooses),
                                                               function ($query) use ($userId) {
                                                                   $query->where('developConsultantId', $userId)
                                                                         ->orWhere('createdByUid', $userId);
                                                               });
                                                 })
                                                 ->when($type, function ($query) use ($status) {
                                                     $query->where('clueStatus',
                                                         OpenShopSiteLocationModel::CLUE_STATUS_5);
                                                 })
                                                 ->when(mb_strlen($filterType),
                                                     function ($query) use ($filterType, $filterValue, $type) {
                                                         if ($filterType == OpenShopOrganizationManageModel::TYPE_COMPANY) {
                                                             //获得分公司所对应的所有省区code
                                                             if ($filterValue != OpenShopOrganizationManageModel::HEADQUARTERS_ID) {
                                                                 $provinceCode = OpenShopOrganizationRegionMappingModel::query()
                                                                                                                       ->where('manageId',
                                                                                                                           $filterValue)
                                                                                                                       ->pluck('provinceCode')
                                                                                                                       ->toArray();
                                                                 $query->whereIn('provinceCode', $provinceCode);
                                                             }
                                                         }
                                                         if ($filterType == OpenShopOrganizationManageModel::TYPE_PROVINCE) {
                                                             //根据省区code去搜索
                                                             $query->where('provinceCode', $filterValue);
                                                         }
                                                         if ($filterType == OpenShopOrganizationManageModel::TYPE_CITY) {
                                                             //根据市区code去搜索
                                                             $query->where('cityCode', $filterValue);
                                                         }
                                                     })
                                                 ->when(!$power['isAll'], function ($query) use ($power) {
                                                     $query->whereRaw($power['rawSql']);
                                                 })
                                                 ->when($cUid > 0, function ($query) use ($cUid) {
                                                     $query->where("createdByUid", $cUid);
                                                 })
                                                 ->with(['uploadFileResourceRel'])
                                                 ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $clueCount    = 0;
        $putCount     = 0;
        $successCount = 0;
        $body         = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());
        $list         = $paginator->map(function ($item) use (&$clueCount, &$putCount, &$successCount, $body) {
            if ($item->uploadFileResourceRel->toArray()) {
                $image = $item->uploadFileResourceRel[0]->formatUrl ?? '';
                foreach ($item->uploadFileResourceRel as $value) {
                    if ($value->position == UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO) {
                        $image = $value->formatUrl;
                    }
                }
            } else {
                $image = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png'; //添加默认图片
            }
            if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_1) {
                ++$clueCount;
            }
            if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                ++$putCount;
            }
            if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6) {
                ++$successCount;
            }
            $cityAreaArr = explode('-', $item->cityArea);
            if (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1]) && isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1] . '-' . $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
            } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1])) {
                $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1];
            } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
            } else {
                $cityArea = '';
            }
            $owner = '-';
            foreach (($body['data'] ?? []) as $user) {
                if ($user['id'] == $item->createdByUid) {
                    $owner = $user['username'];
                }
            }
            return [
                'id'            => $item->id,
                'orderNo'       => $item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6 ? 'FY' . $item->id : $item->orderNo,
                'image'         => $image,
                'address'       => $item->address,
                'cityArea'      => $cityArea,
                'statusText'    => OpenShopSiteLocationModel::CLUE_STATUS_MAP[$item->clueStatus],
                'clueStatus'    => $item->clueStatus,
                'recommender'   => $owner,
                'shopGrade'     => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$item->shopGrade] ?? '',
                'putTime'       => $item->putAt ? date('Y-m-d H:i:s', $item->putAt) : '-',
                'area'          => $item->area ? $item->area . '㎡' : '-',
                'clueRentMonth' => ceil($item->fixedRent / 12),
                'clueRentDay'   => ceil($item->fixedRent / 365),
                'number'        => $item->orderNo,
            ];
        });
        $isShowDetail = true;
        if ($type == OpenShopSiteLocationModel::HOUSE_CLUE_ALL && $power['role'] == \App\Service\OpenShop\SiteLocation\PermissionService::ROLE_ZS) {
            $isShowDetail = false;
        }
        return [
            'list'         => $list,
            'count'        => $paginator->total(),
            'pageNum'      => $pageNum,
            'pageSize'     => $pageSize,
            'clueCount'    => $clueCount,
            'putCount'     => $putCount,
            'successCount' => $successCount,
            'isShowDetail' => $isShowDetail,
        ];
    }


    /**
     * 分公司列表
     * @param $lng
     * @param $lat
     * @param array $manageIds
     * @param int $type
     * @return array
     * @throws GuzzleException
     */
    public static function clueClassify($lng, $lat, array $manageIds = [], int $type = 0): array
    {
        $areaList = collect(RmsAreaRemote::getAreaListAll()['areaList'] ?? []);
        $list     = OpenShopOrganizationManageModel::query()
            ->when(
                $manageIds, function ($query) use ($manageIds) {
                $query->whereIn('id', $manageIds);
            }
            )
            ->with(['regionRel'])
            ->get()
            ->map(
                function ($item) use ($type, $areaList) {
                    $children = [];
                    if ($item->regionRel != null) {
                        foreach ($item->regionRel as $val) {
                            $children[] = [
                                'label'    => $val->provinceName,
                                'type'     => OpenShopOrganizationManageModel::TYPE_PROVINCE,
                                'value'    => $val->provinceCode,
                                'children' => $areaList->where(
                                    'areaPid',
                                    $val->provinceCode
                                )
                                    ->map(
                                        function ($area) use ($type, $areaList) {
                                            $children = [];
                                            if ($type) {
                                                $children = $areaList->where('areaPid', $area['areaId'])
                                                    ->map(
                                                        function ($area) {
                                                            return [
                                                                'label' => $area['cnShortName'],
                                                                'value' => $area['areaId'],
                                                            ];
                                                        }
                                                    )->values()->toArray();
                                            }
                                            return [
                                                'label'    => $area['cnShortName'],
                                                'value'    => $area['areaId'],
                                                'type'     => OpenShopOrganizationManageModel::TYPE_CITY,
                                                'children' => $children,
                                            ];
                                        }
                                    )->values()->filter()->toArray(),
                            ];
                        }
                    }
                    return [
                        'label'    => $item->name,
                        'value'    => $item->id,
                        'type'     => OpenShopOrganizationManageModel::TYPE_COMPANY,
                        'children' => $children,
                    ];
                }
            )->toArray();
        //根据省份匹配对应分公司
        $choosesCompany = [];
        if (!$lng || !$lat) {
            //返货总部
            $choosesCompany = [
                'label' => OpenShopOrganizationManageModel::HEADQUARTERS_TEXT,
                'type'  => OpenShopOrganizationManageModel::TYPE_COMPANY,
                'value' => OpenShopOrganizationManageModel::HEADQUARTERS_ID,
            ];
        } else {
            //根据经纬度去匹配省市区
            $areaArr = AreaService::getAreaCodeByArea($lng, $lat);
            //根据第一个拿到对应省份
            $provinceCode = $areaArr['area'][0]['code'] ?? 0;
            if ($provinceCode) {
                $company = OpenShopOrganizationRegionMappingModel::query()
                    ->where('provinceCode', $provinceCode)
                    ->with(['organizationManageRel'])
                    ->first();
                if ($company != null) {
                    $choosesCompany = [
                        'label' => optional($company->organizationManageRel)->name ?: '',
                        'type'  => OpenShopOrganizationManageModel::TYPE_PROVINCE,
                        'value' => $provinceCode,
                    ];
                }
            }
        }

        return [
            'list'    => $list,
            'chooses' => $choosesCompany,
        ];
    }

    /**
     * 确定已有房源
     * @param $id
     * @param $clueId
     * @return int
     */
    public static function choosesClue($id, $clueId)
    {
        //获得订单对应信息
        $orderNoInfo = OpenShopSiteLocationModel::query()->find($id);
        $clueInfo    = OpenShopSiteLocationModel::query()->find($clueId);
        if ($orderNoInfo == null || $clueInfo == null) {
            throw new ResponseHttpException(BaseErrorCode::$ORDER_NO_ERR);
        }
        $clueOrderNo = $clueInfo->orderNo;
        //已选择过房源线索 如果开店订单中已有绑定的房源  那么就要进行换绑操作 反之直接删除迁移
        if ($orderNoInfo->bindId != OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE) {
            //换绑操作  修复已占房源信息
            OpenShopSiteLocationModel::query()
                                     ->where('id', $id)
                                     ->update([
                                         'bindId'     => OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE,
                                         'orderNo'    => 'FY' . $orderNoInfo->id,
                                         'source'     => OpenShopSiteLocationModel::SOURCE_HOUSING,
                                         'clueStatus' => OpenShopSiteLocationModel::CLUE_STATUS_5,
                                         'siteStatus' => 0,
                                     ]);
            OpenShopSiteLocationCustomerAnalysisModel::query()
                                                     ->where('siteId', $id)
                                                     ->update([
                                                         'orderNo'   => 'FY' . $id,
                                                         'updatedAt' => time(),
                                                     ]);
            OpenShopSiteLocationProductAnalysisModel::query()
                                                    ->where('siteId', $id)
                                                    ->update([
                                                        'orderNo'   => 'FY' . $id,
                                                        'updatedAt' => time(),
                                                    ]);
            OpenShopUploadFileResourceModel::query()
                                           ->where('orderNo', $orderNoInfo->orderNo)
                                           ->update([
                                               'orderNo'   => 'FY' . $id,
                                               'updatedAt' => time(),
                                           ]);
            OpenShopSiteLocationHouseEvaluateModel::query()
                                                  ->where('orderNo', $orderNoInfo->orderNo)
                                                  ->update([
                                                      'orderNo'   => 'FY' . $id,
                                                      'updatedAt' => time(),
                                                  ]);
            OpenShopSiteLocationExamineLogModel::query()
                                               ->withoutGlobalScope('isDel')
                                               ->where('orderNo', $orderNoInfo->orderNo)
                                               ->update([
                                                   'orderNo'   => 'FY' . $id,
                                                   'updatedAt' => time(),
                                               ]);
            WangguiDotWaimaiEstimateModel::query()
                                               ->where('orderNo', $orderNoInfo->orderNo)
                                               ->update([
                                                   'orderNo'   => 'FY' . $id,
                                                   'updatedAt' => time(),
                                               ]);
        } else {
            //删除已有门店选址调查数据
            OpenShopSiteLocationModel::query()
                                     ->where('id', $id)
                                     ->update([
                                         'isDeleted' => 1
                                     ]);

            //删除对应竞品互补品
            OpenShopSiteLocationProductAnalysisModel::query()
                                                    ->where('orderNo', $orderNoInfo->orderNo)
                                                    ->update([
                                                        'isDeleted' => 1
                                                    ]);
            //删除对应客群分析
            OpenShopSiteLocationCustomerAnalysisModel::query()
                                                     ->where('orderNo', $orderNoInfo->orderNo)
                                                     ->update([
                                                         'orderNo'   => $orderNoInfo->orderNo,
                                                         'updatedAt' => time(),
                                                     ]);
            //删除对应门店图片
            OpenShopUploadFileResourceModel::query()
                                           ->where('orderNo', $orderNoInfo->orderNo)   //KD
                //->whereIn('position', UploadFileResourceEnum::SITE_LOCATION_LIST)
                                           ->update([
                    'isDeleted' => 1
                ]);
        }
        //修改对应名称
        if (mb_strlen($clueInfo->shopName)) {
//            ShopService::updateShopName($orderNoInfo->orderNo, $clueInfo->shopName);
        }
        //修改对应房源线索
        $clueInfo->orderNo                = $orderNoInfo->orderNo;
        $clueInfo->bindId                 = $orderNoInfo->id;
        $clueInfo->source                 = OpenShopSiteLocationModel::SOURCE_OPEN_SHOP;
        $clueInfo->mainProcessId          = $orderNoInfo->mainProcessId;
        $clueInfo->chooseShopProvinceCode = $orderNoInfo->chooseShopProvinceCode;
        $clueInfo->clueStatus             = OpenShopSiteLocationModel::CLUE_STATUS_10;
        $clueInfo->siteStatus             = $orderNoInfo->siteStatus;
        $clueInfo->developConsultantId    = $orderNoInfo->developConsultantId;
        $clueInfo->handler                = $orderNoInfo->developConsultantId;
        $clueInfo->developConsultantName  = $orderNoInfo->developConsultantName;
        $clueInfo->save();


        //获取任务ID
        $taskId = (int)CustomerDepartmentSiteLocationRelationModel::query()
            ->where('relationId', $clueId)
            ->value('taskId');

        if ($taskId) {
            // 如果存在关联任务则修改
            // 添加新的选址关联
            $relationModel = CustomerDepartmentSiteLocationRelationModel::query()
                ->updateOrCreate([
                    'taskId'     => $taskId,
                    'relationId' => $clueId,
                ]);

            $oldOrderNo = $relationModel->relationNumber;

            $relationModel->source         = OpenShopSiteLocationModel::SOURCE_OPEN_SHOP;
            $relationModel->relationNumber = $clueInfo->orderNo;
            $relationModel->relationId     = $clueId;
            $relationModel->projectPhase   = 0;
            $relationModel->save();


            CustomerDepartmentOperationLogModel::addLog($taskId, '关联房源和选址', [
                [
                    'theme' => '关联房源和选址',
                    'data'  => [
                        [
                            'key'         => 'orderNo',
                            'beforeValue' => $oldOrderNo,
                            'afterValue'  => $clueInfo->orderNo,
                            'beforeText'  => $oldOrderNo,
                            'afterText'   => $clueInfo->orderNo,
                            'type'        => 1,
                            'description' => '编号变更',
                        ]
                    ]
                ]
            ], $orderNoInfo->developConsultantId);
        }


        //重置任务
        $resetRelationModel = CustomerDepartmentSiteLocationRelationModel::query()
            ->where('relationId', $id)
            ->first();

        if (null != $resetRelationModel) {
            $resetRelationModel->source         = OpenShopSiteLocationModel::SOURCE_HOUSING;
            $resetRelationModel->relationNumber = $clueInfo->orderNo;
            $resetRelationModel->relationId     = $id;
            $resetRelationModel->projectPhase   = 0;
            $resetRelationModel->save();
        }

        //修改评估表单
        OpenShopSiteLocationHouseEvaluateModel::query()
                                              ->where('orderNo', $clueOrderNo)
                                              ->update([
                                                  'orderNo' => $orderNoInfo->orderNo
                                              ]);
        //修改客群分析
        OpenShopSiteLocationCustomerAnalysisModel::query()
                                                 ->where('siteId', $clueId)
                                                 ->update([
                                                     'orderNo'   => $orderNoInfo->orderNo,
                                                     'updatedAt' => time(),
                                                 ]);
        //修改竞品互补品
        OpenShopSiteLocationProductAnalysisModel::query()
                                                ->where('siteId', $clueId)
                                                ->update([
                                                    'orderNo'   => $orderNoInfo->orderNo,
                                                    'updatedAt' => time(),
                                                ]);
        //修改文件图片
        OpenShopUploadFileResourceModel::query()
                                       ->where('orderNo', $clueOrderNo)
                                       ->update([
                                           'orderNo'   => $orderNoInfo->orderNo,
                                           'updatedAt' => time(),
                                       ]);

        //修改审批日志
        OpenShopSiteLocationExamineLogModel::query()
                                           ->where('orderNo', $clueOrderNo)
                                           ->update([
                                               'orderNo'   => $orderNoInfo->orderNo,
                                               'isDeleted' => 1,
                                               'updatedAt' => time(),
                                           ]);

        //修改房源外卖预估
        WangguiDotWaimaiEstimateModel::query()
            ->where('orderNo', $clueOrderNo)
            ->update([
                'orderNo'   => $orderNoInfo->orderNo,
                'updatedAt' => time(),
            ]);

        //        $provinceInfoBy = OrganizationManageService::getProvinceInfoByProvinceCode($orderNoInfo->chooseShopProvinceCode);
//        FeishuMsgSupport::getInstance("有新的房源线索待分配，请注意", [$provinceInfoBy["operationUid"] ?? 0])
//            ->setContent(
//                ["name" => "房源所在区域", "value" => $siteLocationModel->cityArea],
//                ["name" => "任务处理角色", "value" => "省区负责人"],
//                ["name" => "任务名称", "value" => "房源线索调查"],
//                ["name" => "任务处理人", "value" => $provinceInfoBy["operationName"] ?? ""],
//                ["name" => "任务创建时间", "value" => formatDate(time())],
//            )->msgSend(["path" => "pages/house-source/add-source?id={$siteLocationModel->id}"]);
        return $clueId;
    }

    public static function houseClueCount($userInfo, $scope, $filterValue, $filterType)
    {
        $clueCount    = 0;
        $total        = 0;
        $putCount     = 0;
        $successCount = 0;
        //判断用户角色
        $userId        = 0;
        $provinceChief = [];
        if ($scope != PermissionService::PERMISSION_ALL) {
            if ($scope == PermissionService::PERMISSION_DENY) {
                return [];
            }
            if ($userInfo->position == SiteLocationEnum::POSITION_PROVINCE_CHIEF || $scope == PermissionService::PERMISSION_PROVINCE) {
                $provinceChief = OrganizationManageService::getProvinceList($userInfo->userId);
            } else {
                $userId = $userInfo->userId;
            }

        }
        OpenShopSiteLocationModel::query()
                                 ->OfSiteLocaltion($provinceChief, $userId, $userInfo)
                                 ->when(mb_strlen($filterType), function ($query) use ($filterType, $filterValue) {
                                     if ($filterType == OpenShopOrganizationManageModel::TYPE_COMPANY) {
                                         //获得分公司所对应的所有省区code
                                         if ($filterValue != OpenShopOrganizationManageModel::HEADQUARTERS_ID) {
                                             $provinceCode = OpenShopOrganizationRegionMappingModel::query()
                                                                                                   ->where('manageId',
                                                                                                       $filterValue)
                                                                                                   ->pluck('provinceCode')
                                                                                                   ->toArray();
                                             $query->whereIn('provinceCode', $provinceCode);
                                         }
                                     }
                                     if ($filterType == OpenShopOrganizationManageModel::TYPE_PROVINCE) {
                                         //根据省区code去搜索
                                         $query->where('provinceCode', $filterValue);
                                     }
                                 })
                                 ->each(function ($item) use (&$clueCount, &$putCount, &$successCount, &$total) {
                                     if ($item->source == OpenShopSiteLocationModel::SOURCE_HOUSING && $item->bindId == OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE) {
                                         if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_2) {
                                             ++$clueCount;
                                         }
                                         if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                                             ++$putCount;
                                         }
                                         ++$total;
                                     }
                                     if ($item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6) {
                                         ++$successCount;
                                     }
                                 });
        return [
            'clueCount'    => $clueCount,
            'putCount'     => $putCount,
            'successCount' => $successCount,
            'total'        => $total,
        ];
    }


    public static function getApprovalRecord($orderNo)
    {
        $data = OpenShopSiteLocationExamineLogModel::query()
                                                   ->withoutGlobalScope('isDel')
                                                   ->where('orderNo', $orderNo)
                                                   ->orderByDesc('createdAt')
                                                   ->get();

        $body      = RmsUserService::getRmsUserInfoByUserIds($data->pluck('createdByUid')->toArray())['data'] ?? [];
        $userNames = array_column($body, 'username', 'id');

        return $data->map(function ($item) use ($userNames) {
            return [
                'userName'    => $userNames[$item->createdByUid] ?? '',
                'status'      => $item->status,
                'source'      => $item->source,
                'type'        => OpenShopSiteLocationExamineLogModel::SOURCE_MAPPING[$item->source] ?? '-',
                'content'     => $item->content,
                'createdTime' => $item->createdAt->toDateTimeString(),
            ];
        })->toArray();
    }

    public static function replay($rmsUserId, $orderNo, $text)
    {
        $replayModel          = OpenShopSiteLocationReplayModel::query()
                                                               ->where('createdByUid', $rmsUserId)
                                                               ->where('orderNo', $orderNo)
                                                               ->first();
        $replayModel->content = $text;
        $replayModel->save();
    }

    public static function getReplayByOrderNo($orderNo, $userId)
    {
        $replay      = [];
        $notShow     = [];
        $replayModel = OpenShopSiteLocationReplayModel::query()
                                                      ->where('orderNo', $orderNo)
                                                      ->get();

        $userIds  = $replayModel->pluck('createdByUid')->toArray();
        $userInfo = RmsUserService::getRmsUserInfoByUserIds($userIds)['data'] ?? [];
        $userName = array_column($userInfo, 'username', 'id');
        $replayModel->each(function ($item) use ($userName, &$replay, &$notShow) {
            if (mb_strlen($item->content)) {
                $replay[] = [
                    'name'    => $userName[$item->createdByUid] ?? '-',
                    'time'    => $item->updatedAt->toDateTimeString(),
                    'content' => $item->content
                ];
            } else {
                $notShow[] = $item->createdByUid;
            }
        });
        return [
            'list'   => $replay,
            'isShow' => !in_array($userId, $notShow)
        ];
    }

    /**
     * @param $lng
     * @param $lat
     * @return array
     */
    public static function getBaseHouseInfoByLatAndLng($lng, $lat): array
    {
        return AreaService::getAreaCodeByArea($lng, $lat);
    }

    public static function updateClueBasisInfo($userInfo, $clueParams, $orderNo)
    {
        $siteLocationModel = OpenShopSiteLocationModel::query()
                                                      ->where('orderNo', $orderNo)->whereIn('source',
                [
                    OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                    OpenShopSiteLocationModel::SOURCE_HOUSING
                ]);
        $clueStatus        = (int)$siteLocationModel->value('clueStatus');
        //等级
        $levelText = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[$clueParams->cityType] ?? '';

        $standard = GuanyuanDataService::levelCityRentRange($levelText);

        if (($clueParams->clueRent / 100) < $standard['minFourNumber']) {
            $rentGrade = SiteLocationEnum::COST_PERFORMANCE_HIGH;
        } elseif (($clueParams->clueRent / 100) > $standard['maxFourNumber']) {
            $rentGrade = SiteLocationEnum::COST_PERFORMANCE_LOW;
        } else {
            $rentGrade = SiteLocationEnum::COST_PERFORMANCE_MEDIUM;
        }

        if (in_array($clueStatus,
            [OpenShopSiteLocationModel::CLUE_STATUS_12, OpenShopSiteLocationModel::CLUE_STATUS_4])) {
            $clueParams = (array)$clueParams;
            if (isset($clueParams['mallId'])) {
                if ($clueParams['isWhiteList']) {
                    //在白名单中
                    try {
                        $guanyuanData = GuanyuanDataService::getMallDataByMallId($clueParams['mallId'])[0] ?? [];
                    } catch (\Exception $exception) {
                        $guanyuanData = [];
                    }
                    $clueParams['mallProvince']     = $guanyuanData['省份'] ?? '';
                    $clueParams['mallCity']         = $guanyuanData['城市'] ?? '';
                    $clueParams['mallDistrict']     = $guanyuanData['区县'] ?? '';
                    $clueParams['mallArea']         = $guanyuanData['区域'] ?? '';
                    $clueParams['mallAddress']      = $guanyuanData['地址'] ?? '';
                    $clueParams['businessAddress']  = $guanyuanData['地址'] ?? '';
                    $clueParams['businessArea']     = ($guanyuanData['省份'] ?? '') . '-' . ($guanyuanData['城市'] ?? '') . '-' . ($guanyuanData['区县'] ?? '');
                    $clueParams['businessDistrict'] = $guanyuanData['区域'] ?? '';

                } else {
                    //不再白名单中
                    $siteLocationMall = SiteLocationMallModel::query()
                                                             ->where('mallId', $clueParams['mallId'])
                                                             ->first();

                    if (null != $siteLocationMall) {
                        $clueParams['mallProvince']     = $siteLocationMall->province;
                        $clueParams['mallCity']         = $siteLocationMall->city;
                        $clueParams['mallDistrict']     = $siteLocationMall->distinct;
                        $clueParams['mallArea']         = $siteLocationMall->area;
                        $clueParams['mallAddress']      = $siteLocationMall->address;
                        $clueParams['businessAddress']  = $siteLocationMall->address;
                        $clueParams['businessArea']     = $siteLocationMall->province . '-' . $siteLocationMall->city . '-' . $siteLocationMall->distinct;
                        $clueParams['businessDistrict'] = $siteLocationMall->area;
                    }
                }
            }
            //点位到期时间特殊处理
            if (isset($clueParams['nearbyPlaceholderTime'])) {
                $clueParams['placeholderTime'] = strtotime($clueParams['nearbyPlaceholderTime']);
                unset($clueParams['nearbyPlaceholderTime']);
            }
            $wgNumber = '';
            $wgGrade  = 0;
            if (in_array($clueParams['shopModelType'], [SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_SCHOOL])) {
                $wgNumber = $clueParams['wgNumber'] ?? '';
                $wgGrade  = array_search($clueParams['wgGrade'] ?? '', ProgrammingEnum::GRADE_MAPPING) ?: 0;
            }
            unset($clueParams['wgNumber']);
            unset($clueParams['wgGrade']);
            unset($clueParams['wgMatch']);

            if (in_array($clueParams['shopModelType'], [SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_STREET, SiteLocationEnum::SHOP_MODEL_TYPE_COMMUNITY_SCHOOL])) {
                $relationWangguiModel               = OpenShopSiteLocationWangguiRelationModel::query()
                    ->updateOrCreate([
                        'siteId' => $siteLocationModel->value('id')
                    ]);
                $relationWangguiModel->wgNumber     = $wgNumber;
                $relationWangguiModel->grade        = $wgGrade;
                $relationWangguiModel->match        = strlen($wgNumber) ? OpenShopSiteLocationWangguiRelationModel::MATCH_ON : OpenShopSiteLocationWangguiRelationModel::MATCH_OFF;
                $relationWangguiModel->type         = 1;
                $relationWangguiModel->save();
            }



            // 产品定价 菜单等级）选址报告中根据城市等级+选址场景自动调用展示
            $getShopAttribute = self::getShopAttributeByGrade($clueParams);
            unset($clueParams['townText']);
            $clueParams['menuLevel']          = $getShopAttribute['menuLevelId'];         // 产品定价 菜单等级
            $clueParams['siteSelectionGrade'] = $getShopAttribute['siteSelectionGradeId'];// 选址场景分级

            $siteLocationModel->update(array_merge($clueParams, [
                "updatedAt"    => time(),
                "rentGrade"    => $rentGrade,
                "updatedByUid" => $userInfo->userId,
            ]));
        }
    }

    public static function getMapImage($clueParams)
    {
        if (!$clueParams->longitude || !$clueParams->latitude) {
            return (object)[];
        }
        if (is_array($clueParams->siteAddress)) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "网络波动定位失败,请稍后再试");
        }
        $url = self::mapImageUrl($clueParams->longitude, $clueParams->latitude, (string)$clueParams->siteAddress);
        $png = sys_get_temp_dir() . '/' . Str::random() . '.png';
        (new Client())->get($url, [
            'sink' => $png,
        ]);
        //生成热力图图片
        //$heatMapFile = HeatMapService::makeHeatMap($png, $clueParams->longitude, $clueParams->latitude);
        $arr = FileUtil::uploadFile($png);
        //$heatMap = FileUtil::uploadFile($heatMapFile);
        return [
            [
                "position"     => UploadFileResourceEnum::CLUE_PHOTO,
                "url"          => $arr['path'],
                "createdAt"    => time(),
                "createdByUid" => 0,
                "tempFilePath" => $png
            ]
        ];
    }

    /**
     * @param float $longitude
     * @param float $latitude
     * @param string $address
     * @param int $high
     * @param int $width
     * @return string
     */
    public static function mapImageUrl(
        float $longitude,
        float $latitude,
        string $address,
        int $width = 800,
        int $high = 800
    ): string {
        return sprintf(config('area.mapImage'), $longitude, $latitude, $width, $high, mb_substr($address, 0, 15),
            $longitude, ($latitude - 0.001), $longitude, $latitude, WangGuiCityByPower::getRandomAmapKey());
    }

    /**
     * 修改选址的门店模式--二代店 三代店删除了 不更新了
     * @param string $orderNo
     * @param int $shopPattern
     * @param array $patternType
     * @param bool $writeLog
     * @param int $rmsUserId
     * @param string $userName
     * @param array $sellingCategory
     * @return int
     */
    public static function updateShopPattern(
        string $orderNo,
        int $shopPattern,
        array $patternType,
        bool $writeLog = false,
        int $rmsUserId = 0,
        string $userName = '',
        array $sellingCategory = []
    ): int
    {
        if ($writeLog) {
            $oldModel = OpenShopSiteLocationModel::query()
                ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP, OpenShopSiteLocationModel::SOURCE_HOUSING])
                ->where('orderNo', $orderNo)
                ->select(['shopPattern', 'patternType'])
                ->first();

            $oldShopPattern = $oldModel->shopPattern;
            $oldPatternType = $oldModel->patternType;

            $newChanges = [
                "theme"      => '门店模型-销售品类变更',
                "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
                "data"       => [
                    [
                        "key"         => "shopPattern",
                        "beforeValue" => $oldShopPattern,
                        "afterValue"  => $shopPattern,
                        "beforeText"  => OpenShopSiteLocationModel::SHOP_PATTERN_MAPPING[$oldShopPattern] ?? '-',
                        "afterText"   => OpenShopSiteLocationModel::SHOP_PATTERN_MAPPING[$shopPattern] ?? '-',
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => "门店模型"
                    ],
                    [
                        "key"         => "patternType",
                        "beforeValue" => explode(',', $oldPatternType),
                        "afterValue"  => $patternType,
                        "beforeText"  => OpenShopSiteLocationModel::getPatternTypeStr($oldPatternType),
                        "afterText"   => OpenShopSiteLocationModel::getPatternTypeStr(implode(',', Arr::sort($patternType))),
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => "销售品类"
                    ],
                ]
            ];

            ChangeSupport::getInstance()->pushChanges($newChanges);
            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                (int)OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->value('id'),
                OpenShopSignOrderLogModel::UPDATE_ENGINEERING_CONSTRUCTION,
                $userName,
                $rmsUserId
            );
        }

        return OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP, OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->where('orderNo', $orderNo)
            ->update([
//                'shopPattern' => $shopPattern,
//                'patternType' => implode(',', Arr::sort($patternType)),
                'sellingCategory' => implode(',', Arr::sort($sellingCategory)),
            ]);
    }

    public function leaseSubmit($id)
    {
        $verifyPersonnel = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL) ?? [];

        self::$siteLocationModel               = OpenShopSiteLocationModel::getSiteForm($id);
        self::$siteLocationModel->siteStatus   = OpenShopSiteLocationModel::SITE_STATUS_22;
        self::$siteLocationModel->handler      = implode(',', $verifyPersonnel);
        self::$siteLocationModel->ctSubmitTime = time();
        self::$siteLocationModel->save();

        //发送消息
        try {
            $noticeServer = new NoticeService(self::$siteLocationModel->orderNo);
            $noticeServer->setPushUserInfos(ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL));
            $noticeServer->setMissionContent('门店合同审核');
            $noticeServer->setPushUserInfos($verifyPersonnel);
            $noticeServer->siteLocationAuditJob('审核');
        } catch (\Exception $exception) {
            Log::info("门店Code" . (int)optional(self::$siteLocationModel->signOrderRel)->shopCode . "商家已确认选址，给核实人员发送消息失败");
        }
    }


    public static function leaseReject($userInfo, $id, $content)
    {
        //驳回租赁合同信息 状态变更为合同待上传， 给开发发送消息
        self::$siteLocationModel = OpenShopSiteLocationModel::query()
            ->where('id', $id)
            ->first();

        if (self::$siteLocationModel->siteStatus != OpenShopSiteLocationModel::SITE_STATUS_22) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '该状态不允许驳回操作');
        }

        //修改状态
        self::$siteLocationModel->siteStatus = OpenShopSiteLocationModel::SITE_STATUS_21;
        self::$siteLocationModel->handler    = self::$siteLocationModel->developConsultantId;
        self::$siteLocationModel->save();

        //添加日志
        (new OpenShopSiteLocationExamineLogModel([
            'orderNo'      => self::$siteLocationModel->orderNo,
            'content'      => $content,
            'position'     => OpenShopSiteLocationExamineLogModel::POSITION_VERIFY_PERSONNEL,
            'status'       => OpenShopSiteLocationExamineLogModel::STATUS_REFUSE,
            'source'       => OpenShopSiteLocationExamineLogModel::SOURCE_LEASE_CONTRACT,
            'createdByUid' => $userInfo->userId,
            'updatedByUid' => $userInfo->userId,
        ]))->addData();
        $userList = RmsUserService::getRmsUserInfoByUserIds(array_merge([self::$siteLocationModel->developConsultantId], ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL)))['data'] ?? [];
        $userData = array_column($userList, null, 'id');
        //给选址通知群发消息
        $json = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/leaseContractReject.json')),
                (int)optional(self::$siteLocationModel->signOrderRel)->shopCode,
                self::$siteLocationModel->developConsultantName,
                self::$siteLocationModel->address,
                self::$siteLocationModel->cityArea,
                $userData[$userInfo->userId]['username'] ?? '-',
                Carbon::now()->toDateTimeString(),
                $content,
                BaseService::getSiteLocationAppletUrl(0, self::$siteLocationModel->orderNo),
                (int)optional(self::$siteLocationModel->signOrderRel)->shopCode
            ), true
        );
        //给开发负责人发消息
        MessageSendService::sendMessage($userData[self::$siteLocationModel->developConsultantId]['feishuUserId'] ?? '513296d9', 'user_id', $json, 'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);

    }



    /**
     * 合同审批通过
     * @param $userInfo
     * @param $id
     * @return void
     * @throws GuzzleException
     */
    public static function leasePass($userInfo, $id)
    {
        self::$siteLocationModel = OpenShopSiteLocationModel::query()
            ->where('id', $id)
            ->first();

        if (self::$siteLocationModel->siteStatus != OpenShopSiteLocationModel::SITE_STATUS_22) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '该状态不允许驳回操作');
        }

        //修改状态
        self::$siteLocationModel->siteStatus = OpenShopSiteLocationModel::SITE_STATUS_4;
        self::$siteLocationModel->handler    = '';
        self::$siteLocationModel->save();

        //添加日志
        (new OpenShopSiteLocationExamineLogModel([
            'orderNo'      => self::$siteLocationModel->orderNo,
            'position'     => OpenShopSiteLocationExamineLogModel::POSITION_VERIFY_PERSONNEL,
            'status'       => OpenShopSiteLocationExamineLogModel::STATUS_OK,
            'source'       => OpenShopSiteLocationExamineLogModel::SOURCE_LEASE_CONTRACT,
            'createdByUid' => $userInfo->userId,
            'updatedByUid' => $userInfo->userId,
        ]))->addData();
        $userList = RmsUserService::getRmsUserInfoByUserIds(array_merge([self::$siteLocationModel->developConsultantId], ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL)))['data'] ?? [];
        $userData = array_column($userList, null, 'id');
        //给选址通知群发消息
        $json = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/leaseContractPass.json')),
                (int)optional(self::$siteLocationModel->signOrderRel)->shopCode,
                self::$siteLocationModel->developConsultantName,
                self::$siteLocationModel->address,
                self::$siteLocationModel->cityArea,
                $userData[$userInfo->userId]['username'] ?? '-',
                Carbon::now()->toDateTimeString(),
                BaseService::getSiteLocationAppletUrl(0, self::$siteLocationModel->orderNo),
                (int)optional(self::$siteLocationModel->signOrderRel)->shopCode
            ), true
        );
        //给开发负责人发消息
        MessageSendService::sendMessage($userData[self::$siteLocationModel->developConsultantId]['feishuUserId'] ?? '513296d9', 'user_id', $json, 'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);
    }

    public static function transferHouse($userId, $managerId, $id)
    {
        //获得用户信息
        $userInfo = RmsUserService::getRmsUserInfoByUserIds($managerId)['data'][0] ?? [];
        //修改开发经理
        $siteLocationModel = OpenShopSiteLocationModel::query()->find($id);
        if (null == $siteLocationModel) {
            return;
        }
        if (OpenShopSiteLocationModel::CLUE_STATUS_5 != $siteLocationModel->clueStatus) {
            throw new ResponseHttpException(10000, null, '该房源当前状态禁止转让');
        }


        $oldManager = $siteLocationModel->developConsultantName;
        $siteLocationModel->developConsultantName = $userInfo['username'];
        $siteLocationModel->developConsultantId   = $userInfo['id'];
        $siteLocationModel->save();

        //添加日志
        (new OpenShopSiteLocationExamineLogModel([
            'orderNo'      => $siteLocationModel->orderNo,
            'source'       => OpenShopSiteLocationExamineLogModel::SOURCE_TRANSFER_HOUSE,
            'content'      => '【房源转让】由' . $oldManager . '转给' . $userInfo['username'],
            'position'     => OpenShopSiteLocationExamineLogModel::POSITION_OTHER_EXAMINE,
            'status'       => OpenShopSiteLocationExamineLogModel::STATUS_OK,
            'createdByUid' => $userId,
            'updatedByUid' => $userId,
        ]))->addData();

    }

    /**
     * 是否迁址店
     * @param Model $item
     * @return bool
     */
    public static function tagLocationStatus(Model $item): bool
    {
        $tagLocationStatus = false;
        if (!empty(($item->mainProcessRel->childLocationOrder))) {
            $tagLocationStatus = (bool)($item->mainProcessRel->childLocationOrder);
        } else {
            if (!empty($item->mainProcessRel) && count($item->mainProcessRel->getRelationsLocationOrderNos()) > 0) {
                $tagLocationStatus = true;
            }
        }

        return $tagLocationStatus;
    }



    //生成热力图图片
    public static function getHeatMap()
    {
        try {
            //获得外卖热力图图片
            $image = OpenShopUploadFileResourceModel::query()
                ->where('orderNo', self::$siteLocationModel->orderNo)
                ->where('position', UploadFileResourceEnum::TAKE_OUT_HEATMAP)
                ->where('businessId', 0)
                ->value('url');
            if (strlen($image)) {
                $heatMapImage = picturePath($image);
            } else {
                //生成热力图
                $lng = self::$siteLocationModel->longitude;
                $lat = self::$siteLocationModel->latitude;
                $key = WangGuiCityByPower::getRandomAmapKey();
                $amapUrlTemp = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=1024*1024&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=' . $key;
                $url         = sprintf($amapUrlTemp, $lng, $lat, $lng, $lat, '', $lng, ($lat + 0.001));
                $png = sys_get_temp_dir() . '/' . Str::random() . '.png';
                (new Client())->get($url, [
                    'sink' => $png,
                ]);
                $heatMap = FileUtil::uploadFile(HeatMapService::makeHeatMap($png, $lng, $lat));
                $heatMapImage = $heatMap['url'] ?? '';
                //上传文件
                $uploadFileModel           = OpenShopUploadFileResourceModel::query()->firstOrNew([
                    'orderNo'  => self::$siteLocationModel->orderNo,
                    'position' => UploadFileResourceEnum::TAKE_OUT_HEATMAP,
                ]);
                $uploadFileModel->url      = $heatMap['path'];
                $uploadFileModel->isPublic = 1;
                $uploadFileModel->save();
                @unlink($heatMapImage);
            }
        } catch (\ErrorException $exception) {
            $heatMapImage = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png';
        }
        return $heatMapImage;
    }

    /**
     * 获取场景等级，菜品定价 从商场，街道等级中获取
     * @param $clueParams
     * @return array
     */
    public static function getShopAttributeByGrade($clueParams): array
    {
        $gradeText = '';
        if ($clueParams['mallGrade']) {
            $gradeText = str_replace('级', '', $clueParams['mallGrade']);
        } else {
            if (strpos($clueParams['townText'], 'A') !== false) {
                $gradeText = 'A';
            }
            if (strpos($clueParams['townText'], 'B') !== false) {
                $gradeText = 'B';
            }
            if (strpos($clueParams['townText'], 'C') !== false) {
                $gradeText = 'C';
            }
            if (strpos($clueParams['townText'], 'D') !== false) {
                $gradeText = 'D';
            }
            if (strpos($clueParams['townText'], 'S') !== false) {
                $gradeText = 'S';
            }
        }
        $menuLevelId = $siteSelectionGradeId = 0;
        $getShopAttributeData = CommonService::getShopAttributeData();// rms门店属性配置
        if ($gradeText) {
            $siteSelectionGrade   = collect($getShopAttributeData)
                ->where('id', SiteLocationEnum::CATEGORY_ID_5)// 选址场景分级 单选 S A B C D
                ->first();
            if ($siteSelectionGrade) {
                foreach ($siteSelectionGrade['value'] as $v) {
                    if ($gradeText == $v['name']) {
                        $siteSelectionGradeId = $v['id'];
                    }
                }
            }
        }

        // 获取 城市菜单等级
        if ($clueParams['cityCode']) {
            $cityGradeInfo = RmsAreaRemote::getCityGrade($clueParams['cityCode'])['cityInfo'] ?? [];
            $cityMenuLevel = $cityGradeInfo['menuLevel'] ?? '';

            $menuLevelData = collect($getShopAttributeData)
                ->where('id', SiteLocationEnum::CATEGORY_ID_11)// 产品定价 菜单等级
                ->first();
            if ($menuLevelData) {
                foreach ($menuLevelData['value'] as $v) {
                    if (strpos($v['name'], $cityMenuLevel) !== false) {
                        $menuLevelId = $v['id'];
                        break;
                    }
                }
            }
        }
        return [
            'menuLevelId'          => $menuLevelId,
            'siteSelectionGradeId' => $siteSelectionGradeId,
        ];
    }
}
